Explain the Object in Javascript, javascriptobject

Source: Internet
Author: User
Tags hasownproperty

Explain the Object in Javascript, javascriptobject

Objects are a common type in javascript, and all objects in javascript are inherited from Object objects. Although we usually simply use Object objects to store data and do not use many other functions, Object objects actually contain many useful attributes and methods, in particular, the methods added by ES5. Therefore, this article will begin with the most basic introduction and detail the common methods and applications of objects.

Basic Introduction

Create object

First, we all know that an object is a set of similar data and functions. We use it to simulate objects in the real world. In Javascript, there are two methods to create an object: constructor and object literal.

New constructor Method

Var person = new Object (); person. name = "Wolf's blue Fat Man"; person. age = 25;

This method uses the new Keyword, keeps up with the Object constructor, and then dynamically adds different attributes to the Object instance. This method is relatively cumbersome. It is generally recommended to use the object literal volume to create an object.

Object literal

The object literal is easy to understand. It is simple and convenient to directly create an object in the form of key/value.

Var person = {name: "Wolf's blue Fat Man", age: 25 };

In this way, the object attributes are directly wrapped in curly brackets, and the object attributes are created using key/value. Each attribute is separated by a comma.
NOTE: If it is the last attribute, do not add a comma after it, because an error will be reported in some old browsers.

Attributes and methods of object instances

No matter which method is used to create an object instance, the instance will have the following attributes and methods, which will be described below.

Constructor attributes

The constructor attribute stores the constructor of the current Object. In the previous example, the constructor saves the Object method.

var obj1 = new Object();obj1.id = "obj1";var obj2 = {  "id": "obj2"}; console.log(obj1.constructor);//function Object(){}console.log(obj2.constructor);//function Object(){}

HasOwnProperty (propertyName) Method

The hasOwnProperty method receives a string parameter, which indicates the property name, used to determine whether the property is in the current object instance, rather than in the prototype chain of the object. Let's take a look at the following example:

var arr = [];    console.log(arr.hasOwnProperty("length"));//trueconsole.log(arr.hasOwnProperty("hasOwnProperty"));//false

In this example, we first define the arr instance of an array Object. We know that the array Object actually inherits the Object through the prototype chain, and then has its own attributes, the hasOwnProperty method is used to determine that length is an attribute of arr, while hasOwnProperty is an attribute of the prototype chain.
The hasOwnProperty method can be used with for... in to obtain the object's own key.

IsPrototypeOf (Object) Method

The isPrototype method receives an object to determine whether the current object is in the prototype chain of the input parameter object. This is a bit abstract. Let's look at the code.

function MyObject() {}var obj = new MyObject();console.log(Object.prototype.isPrototypeOf(obj));

We know that MyObject inherits from the Object, and in JS, inheritance is implemented through prototype. Therefore, the prototype of the Object must be in the prototype chain of the MyObject Object instance.

PropertyIsEnumerable (prototypeName) Method

PrototypeIsEnumerable is used to determine whether a given attribute can be enumerated by the for .. in statement. See the following code:

var obj = {name: "objName"} for (var i in obj) {console.log(i);}

Run this code to output the string "name... The in statement can obtain the obj name attribute, but we know that there are many obj attributes, such as constructor, hasOwnPrototype, but they are not output, indicating that these attributes cannot be... The in can be obtained through the propertyIsEnumerable method.

Copy codeThe Code is as follows:
Console. log (obj. propertyIsEnumerable ("constructor"); // false

Determine whether the "constructor" can be enumerated. If the output is false, the "constructor" cannot be enumerated.

ToLocaleString () method

The toLocalString method returns the string representation of the object, which is related to the code execution environment.

Var obj ={}; console. log (obj. toLocaleString (); // [object Object] var date = new Date (); console. log (date. toLocaleString (); // 1:39:27

ToString () method

ToString is used to return the string representation of an object.

Var obj ={}; console. log (obj. toString (); // [object Object] var date = new Date (); console. log (date. toString (); // Sun Feb 28 2016 13:40:36 GMT + 0800 (China Standard Time)

ValueOf () method

The valueOf method returns the original value of an object, which may be a string, value, or bool value.

var obj = {  name: "obj"};console.log(obj.valueOf());//Object {name: "obj"}var arr = [1];console.log(arr.valueOf());//[1]var date = new Date();console.log(date.valueOf());//1456638436303

As shown in the code, three different object instances call valueOf to return different data.

Attribute type

In Javascript, there are two types of attributes: data attributes and accessors attributes. Let's take a look at what these two attributes are.

Data attributes

Data attributes can be understood as the attributes assigned when we define objects at ordinary times. They can be read and written. However, ES5 defines some features that are used to describe various features of an attribute. The features are internal values and cannot be accessed directly. Features are represented by square brackets, such as [[Enumerable]. Attribute features have some default values. to modify the default value of a feature, you must use the new Object. defineProperty method defined by es5.
Data attributes have four features that describe their features. The following describes each feature in sequence:
(1) [[resumable]: indicates whether the attribute can be deleted using the delete operator. The default value is true.

var obj = {};obj.name = "myname";    delete obj.name;console.log(obj.name);//undefined

This Code clearly indicates that after deleting the name attribute of obj through delete, we will not be able to access the name attribute again.
We use the Object. defineProperty method to modify the [[resumable] feature.

var obj = {};obj.name = "myname";Object.defineProperty(obj, "name", {  configurable: false})        delete obj.name;console.log(obj.name);//myname

After the resumable attribute is set to false, the delete operation cannot delete the name attribute. If you delete the attribute in strict mode, an error is returned.

(2) [[Enumerable]: Indicates whether to pass... The in statement is used to enumerate attributes. The default value is true.
Let's take a look at the previous example:

var obj = {  name: "objName"} for (var i in obj) {  console.log(i);//name}

This Code only outputs the name attribute. Set [[Enumerable] of the constructor attribute to true.

var obj = {    name: "objName"}Object.defineProperty(obj, "constructor", {  enumerable: true})for (var i in obj) {  console.log(i);//name,constructor}console.log(obj.propertyIsEnumerable("constructor"));//true

In this Code,... The in loop gets two attributes: name and constructor, And the propertyIsEnumerable method is used to judge whether the constructor returns true.

(3) [[Writable]: indicates whether the attribute value can be modified. The default value is true.
If [[Writable] is set to false, the modification attempt will fail and an error will be reported in strict mode.

(4) [[Value]: indicates the attribute Value. The default Value is undefined.

Let's look at these two features through a simple example:

var obj = {  name: "name"};console.log(obj.name);//name    Object.defineProperty(obj, "name", {  value: "newValue",  writable: false})console.log(obj.name);//newValueobj.name = "oldValue";console.log(obj.name);//newValue

We first define the property value of the obj object name as "name", then use the defineProperty method to modify the value, and set it to unchangeable. Then we can modify the value of the name attribute to find that the modification is invalid.
Can we modify the value of the name attribute through defineProperty? The answer is yes:

Object.defineProperty(obj, "name", {  value: "oldValue"})console.log(obj.name); //oldValue

Accessors

The accessors property is a bit similar to the property in C #. the difference with the data property is that it does not have the [[Writable] and [Value] features of the data property, instead, it has a pair of getter and setter functions.
[[Get]: The function called to read the attribute. The default value is undefined.
[[Set]: The function called when setting properties. The default value is undefined.
Getter and setter are very useful. Assume there are two attributes. The second attribute value changes with the change of the first attribute value. This scenario is very common at the beginning of our usual encoding. In the previous practice, we often need to manually modify the value of the second attribute. Now we can solve this problem through the get and set functions. Let's look at the example below:

Var person = {age: 10} Object. defineProperty (person, "type", {get: function () {if (person. age> 17) {return "adult";} return "child" ;}}) console. log (person. type); // child person. age = 18; console. log (person. type); // adult

By modifying the value of age, the value of type is also modified accordingly, so that we do not need to manually modify the value of type.
The following method can achieve the same effect:

Var person = {_ age: 10, type: ""} Object. defineProperty (person, "age", {get: function () {return this. _ age ;}, set: function (newValue) {this. _ age = newValue; this. type = newValue> 17? "Adult": "child" ;}}) console. log (person. type); person. age = 18; console. log (person. type );

Pay attention to the following points about accessors:
1. In strict mode, both get and set must be set.
2. In non-strict mode, you can set only one of them. If you only set get, the attribute is read-only. If you only set, the attribute cannot be read.
3. Object. defineProperty is a new method in ES5. IE9 (partial implementation of IE8, only supported by dom objects) is not supported by the following browsers. Some old browsers can use non-standard methods defineGetter () and defineSetter () if you are interested, you can find the relevant information.

Methods related to feature operations

ES5 provides some methods for reading or operating attribute features. The Object. defineProperty used earlier is one of them. I have summarized some common methods as follows:

(1) Object. defineProperty
Defines the attributes of an object. This method has been used many times before.

Copy codeThe Code is as follows:
Object. defineProperty (obj, propName, descriptor );

DefineProperty is somewhat similar to the static method scheduled on the Object. It is called directly through the Object, and it receives three parameters:
Obj: the object to define the attribute
PropNane: name of the property to be defined
DefineProperty: attribute descriptor, which includes the property definition.
Example:

var obj = {};Object.defineProperty(obj, "name", {  value: "name",  configurable: true,  writable: true,  enumerable: true});

(2) Object. defineProperties
Similar to defineProperty, it is used to define object attributes. The difference is that it can be used to define multiple attributes at the same time. We can also see it through naming. The usage is as follows:

var obj = {};Object.defineProperty(obj, {  "name": {    value: "name",    configurable: true,    writable: true,    enumerable: true  },  "age": {    value: 20   }});

(3) Object. getOwnPropertyDescriptor
ES5 also provides a method to read feature values. This method receives an object and its attribute names as two parameters and returns an object based on the different attribute types, the returned object contains different values.

Var person = {_ age: 10, type: ""} Object. defineProperty (person, "age", {get: function () {return this. _ age ;}, set: function (newValue) {this. _ age = newValue; this. type = newValue> 17? "Adult": "child" ;}}) console. log (Object. getOwnPropertyDescriptor (person, "type"); // Object {value: "adult", writable: true, enumerable: true, retriable: true} console. log (Object. getOwnPropertyDescriptor (person, "age"); // Object {enumerable: false, retriable: false, get: function (), set: function ()}

Object Method

In ES5, a batch of methods are added to the Object, which can be accessed directly through the Object. The previously used defineProperty is one of the newly added methods. There are many other methods. I will summarize them as follows:

Object Creation Method

Object. create (proto, [propertiesObject])

As mentioned above, there are two methods to create an object: constructor and object literal volume.
One disadvantage of the two methods is that if you want to create multiple objects, it is very complicated to write, so you will have a method to create a custom constructor to create objects, as follows:

function Person(name, age) {  this.name = name;  this.age = age;}var person = new Person("Jack", 15);

This method allows you to easily create multiple identical objects. It is also a commonly used method.

The Object. create method provided by ES5 is also a method for creating objects. This method allows you to select a prototype Object for the created Object without defining a constructor. The usage is as follows:

var obj = Object.create(Object.prototype, {   name: {    value: "Jack"  }})console.log(obj.name);//Jack

The first parameter received by this method is used as the prototype of the created object, and the second parameter is the object property. Note: In this example, the name attribute cannot be modified because it does not set the writable attribute. The default value is false.
In my opinion, Object. create is a cumbersome method for creating objects. Unless you need to modify attributes, we do not recommend using this method to create objects.

Attribute Retrieval Method

Object. keys

Object. keys is the attribute name used to obtain all the enumerated attributes of a given Object. It returns an array.

function Parent() {  this.lastName = "Black"}function Child(firstName) {  this.firstName = firstName;}Child.prototype = new Parent();var son = new Child("Jack");console.log(Object.keys(son));//["firstName"]

The Code returns the firstName and does not return the lastName and unenumerable attributes inherited from prototype.
In some old browsers, we can use hasOwnProperty and... In to achieve similar results.

Object.keys = Object.keys ||  function (obj) {    var keys = [];    for (var key in obj) {      if (obj.hasOwnProperty(key)) {        keys.push(key);      }    }    return keys;  }Object.getOwnPropertyNames()

GetOwnPropertyNames is used to obtain all the attributes of an object, including the enumerated and non-enumerated attributes, as shown below:

function Parent() {  this.lastName = "Black"}function Child(firstName) {  this.firstName = firstName;}Child.prototype = new Parent();var son = new Child("Jack");Object.defineProperty(son, "age", {  enumerable: false})console.log(Object.keys(son));//["firstName"] console.log(Object.getOwnPropertyNames(son));//["firstName", "age"]


We defined a non-enumeration attribute age for the son object, and then obtained the attribute list through the keys and getOwnPropertyNames methods. The difference between the two is obvious.

Attribute feature Method

This is mainly the three methods mentioned above: defineProperty, defineProperties and getOwnPropertyDescriptor.

Object restriction Method

ES5 provides a series of methods to restrict object modification to prevent errors caused by accidental modification of some objects. Each type of restriction includes a judgment method and a setting method.

Block object extension

Object. preventExtensions () is used to restrict the extension of an Object. After the Object is set, new attributes cannot be added to the Object. The usage is as follows:

Copy codeThe Code is as follows:
Object. preventExtensions (obj );

This method receives an object that cannot be expanded as a parameter. Pay attention to the following two points:
1. attributes of an object cannot be extended, but existing attributes can be deleted.
2. failed to add a new property means that the property cannot be added to itself. If it is on the object prototype, you can still add the property.

function Person(name) {  this.name = name;}var person = new Person("Jack");Object.preventExtensions(person);delete person.name;console.log(person.name);//undefinedPerson.prototype.age = 15;console.log(person.age);//15

The Object. isExtensible method is used to determine whether an Object can be expanded. The default value is true.

Sealing objects

Object. seal can seal an Object and return the Object to be sealed.
The sealed object cannot add or delete existing attributes, nor can it modify the enumerable, writable, and retriable attributes, but the attribute values can be modified.

function Person(name) {  this.name = name;}var person = new Person("Jack");Object.seal(person);delete person.name;console.log(person.name);//Jack

After the object is sealed, delete is used to delete the object attribute. You can still access the attribute.

Object. isSealed can be used to determine whether an Object is sealed.

Freeze object

The Object. freeze method is used to freeze an Object. Frozen objects cannot be added, modified, or deleted. Attribute attribute feature values cannot be modified. That is, the Object cannot be modified.

function Person(name) {  this.name = name;}var person = new Person("Jack");Object.freeze(person);delete person.name;console.log(person.name);//JackPerson.prototype.age = 15;console.log(person.age);//15

By analyzing the code above, we can find that frozen objects cannot delete their own attributes, but they can still be added through their prototype objects.

Object. isFrozen can be used to determine whether an Object is frozen.

We can find that the methods of these three restricted objects are increasing in degree of restriction.

Summary

Although an Object is the most frequently used Object in our daily development, many of its functions have not been mined by us. This article first introduces the basic usage of the Object, then introduces some rarely used attribute features, and finally analyzes some commonly used methods, especially the new methods provided in es5. Welcome to our discussion !!

Address of this article: http://luopq.com/2016/02/28/object-in-javascript/. For more information, see.

Articles you may be interested in:
  • Javascript Object)
  • About prototype of a Javascript object
  • Javascript Object learning notes
  • How to create an object and operate on object Attributes in JavaScript
  • A new method for creating javascript objects: Object. create ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.