Describes the attributes and features of JavaScript.

Source: Internet
Author: User
This article describes the nature of objects in JavaScript, the relationship between objects and classes, the relationship between objects and reference types, how object attributes are classified, and the uniqueness of attributes. If you are interested, you can see that the attributes and features in JavaScript are completely different. Here, I will take a deep understanding of the attributes and features in JavaScript based on what I have learned.

The main content is as follows:

Understanding the nature of objects in JavaScript, the relationship between objects and classes, and the relationship between objects and reference types

How to classify Object Attributes

Special understanding of attributes

Part 1: understanding the nature of objects in JavaScript, the relationship between objects and classes, and the relationship between objects and reference types

The essence of an object: A ECMA-262 defines an object as a set of unordered attributes that can contain basic values, objects, or functions. That is, an object is a group of values without specific sequence. Each attribute or method of an object has a name, and this name is mapped to a value. Therefore, an object is essentially a hash: A group of name-value pairs, whose values can be data or functions.

Relationship between objects and classes: In JavaScript, objects and classes have no relationship. This is because the root of ECMAScript does not have the concept of class, and its objects are different from those in other class-based languages.

Relationship between objects and reference types: objects and reference types are not equivalent, because each object is created based on a reference type.

Part 2: how to classify Object Attributes

Objects Created by constructors or object literal methods have attributes and methods (attributes and methods must belong to objects as long as they are mentioned, it must have attributes and methods (except for custom attributes). attributes can be divided into data attributes and accessors attributes. Their differences are as follows:

Data attributes are generally used to store data values. accessors attributes do not contain data values.

Accessors are mostly used for get/set operations.

Part 3: special understanding of attributes

ECMAScript defines the attribute concept to describe various features of an object property. That is to say, the feature is different from the attribute to describe the attribute. Next, I will explain them separately:

Data attributes and features

Accessors attributes and features

How to Use the Object. defineProperties () method to define multiple features

How to Use the Object. getOwnPropertyDescripter () method to read the attribute descriptor to read the attribute features

1. Data attributes and features

As we have just said, the data attribute is used to store data values. Therefore, the data attribute has a location where data values can be read and written. The data attribute has four characteristics that describe its behavior. Because ECMAScript stipulates that the attribute cannot be directly accessed in JavaScript (Note: Not inaccessible ), so we put it in square brackets. As follows:

[[Retriable]: The default value is true, a. whether to delete the attribute through delete to redefine attribute B. Whether to modify the attribute c. Whether to modify the attribute from the data attribute to the accessors attribute

[[Enumerable]: The default value is true, indicating whether this attribute can be returned through a for-in loop (so if it is false, the for-in loop cannot enumerate its attributes)

[[Writable]: The default value is true, indicating whether the attribute value can be modified. This is different from [[retriable.

[[Value]: The default Value is undefined. This Value is the attribute Value. You can read or write the attribute Value at this position.

Note: The above default refers to the attributes of the Object created by the constructor or Object literal, rather than the Object. defineProperty () method to be introduced below.

All these features have default values, but what should we do if these default values are not what we want? Of course it is modified! We can use the Object. defineProperty () method to modify the default attribute features. DifineProperty is the meaning of the defined attribute. This method receives three parameters: the object where the attribute is located, the name of the attribute, and a descriptor object. The third parameter descriptor object is created by using the object literal method. The attributes and attribute values in the object actually save the attributes and attribute values to be modified.

The following are several examples for further understanding.

A

var person={};Object.defineProperty(person,"name",{  writable:false,  value:"zhuzhenwei"});console.log(person.name);//zhuzhenweiperson.name="heting";console.log(person.name);//zhuzhenwei

Here, I created an object using the object literal method, but I didn't create both methods and properties. Instead, the Object. defineProperty () method is used to create attributes and modify the default values. Here, writable is set to false, so it is invalid when I try to modify person. name later.


B

var person={};Object.defineProperty(person,"name",{  value:"zhuzhenwei"});console.log(person.name);//zhuzhenweiperson.name="heting";console.log(person.name);//zhuzhenwei

Note: In this example, writable: false is deleted. Why cannot it be modified? This is because when I introduced features, the first three are true by default, which is obtained when an object is created and attributes are created. For properties created by calling the Object. defineProperty () method, the default values of the first three features are false.


C

var person={};Object.defineProperty(person,"name",{  value:"zhuzhenwei",  configurable:false});console.log(person.name);//zhuzhenweidelete person.name;console.log(person.name);//zhuzhenwei

Here, we set the new property name feature to retriable: false; therefore, the following operation to delete the property is invalid. According to B, the default value of retriable is false. It cannot be modified even if it is removed.


D

var person={};Object.defineProperty(person,"name",{  value:"zhuzhenwei",  configurable:true});console.log(person.name);//zhuzhenweidelete person.name;console.log(person.name);//undefined 

Here, I changed the default retriable value from the default false value to true, and changed it to configurable. Then, it was deleted successfully.

E

var person={};Object.defineProperty(person,"name",{  value:"zhuzhenwei",  configurable:false});console.log(person.name);//zhuzhenweiObject.defineProperty(person,"name",{  value:"zhuzhenwei",  configurable:true});console.log(person.name);//Uncaught TypeError: Cannot redefine property: name(…)

If it has already been set to false, it is futile to change it to true later. That is, once the attribute is set to unconfigurable, it cannot be changed back to configurable.


F

console.log(person.name);//Uncaught TypeError: Cannot redefine property: name(…)var person={};Object.defineProperty(person,"name",{  value:"zhuzhenwei",});console.log(person.name);//zhuzhenweiObject.defineProperty(person,"name",{  value:"zhuzhenwei",  configurable:true});console.log(person.name);//Uncaught TypeError: Cannot redefine property: name(…)

It can be noted that, even if we do not care about the default retriable: false in the previous step, what we get is still not configurable. Therefore, we can conclude that the default value must be changed to true when the Object. defineProperty () function is called for the first time for configuration.

2. accessors attributes and features

As mentioned earlier, accessors do not contain data values. They contain a pair of getter functions and setter functions (these two functions are not required ). When reading the accessors attribute, the getter function is called, which returns valid values. When writing the accessors attribute, the setter function is called and a new value is passed in, this function determines how data is processed. Similarly, because you cannot directly access the features of the accessors through JavaScript, the features listed below will be included in [] for differentiation.

[[Retriable]: The default value is true, a. whether to delete the attribute through delete to redefine attribute B. Whether to modify the attribute c. Whether to modify the attribute from the accessor attribute to the Data Attribute

[[Enumerable]: The default value is true, indicating whether this attribute can be returned through a for-in loop (so if it is false, the for-in loop cannot enumerate its attributes)

[[Get]: The function called when the attribute is read. The default value is undefined. Key: The feature can be a function.

[[Set]: The function called when writing an attribute. The default value is undefined. The key is that a feature can be a function. Because get and set functions are also attribute features, they may be possible (probably because these two functions are not required) appears in Object. in the attributes of the third parameter descriptor object of defineproperty.

Note: 1. Compared with the data property, we found that the accessors property does not have the writable and value features. This is because the accessors attribute does not contain data values. Of course, we cannot modify the attribute values (the writable attribute is not used), so we do not need to consider values.

2. The accessors attribute cannot be defined directly. It must be defined using Object. defineProperty. (Through this rule, we can accurately determine the attributes and data attributes of the visitor)

The following example is used for in-depth understanding:

var book={  _year:2004,  edition:1};Object.defineProperty(book,"year",{  get:function(){
            return this._year; }, set:function(newValue){ if(newValue>2004){ this._year=newValue; this.edition+=newValue-2004; } }});book.year=2005;console.log(book.edition);//2

A few areas that require in-depth understanding:

1. the accessors attribute cannot be defined directly. The Object must be used. defineProperty () is defined, and this property has the set and ger features, so we can judge that _ year and edition are data attributes, and year is the accessors attribute.

2. We can see that the _ year data attribute starts with _ (underline). This is a common mark used to indicate attributes that can only be accessed through object methods. From the above example, we can see that get is equivalent to a method of the descriptor object, and _ year is the attribute accessed in this object method. Edition can be accessed either through object methods or directly by objects.

3. book. year indicates that the accessors attribute is being read. The get function is called and a valid value of 2004 is returned.

4. book. year = 2005 indicates the write accessors attribute. In this case, the set function is called and a new value is passed in. 2005 is sent to newValue. This function determines how to process data.

5. In this case, the common method of using the accessors property is to set the value of an attribute, which may change other attributes.


3. How to Use the Object. defineProperties () method to define multiple features

Obviously, an Object cannot have only one attribute. Therefore, it is very likely to define multiple attributes. Therefore, JavaScript provides the Object. defineProperties () method to solve this problem. This method receives two parameters. The first parameter is the object where the attribute is to be defined, and the second parameter is the object created by the object literal method. The attribute name of the object is the name of the feature to be defined, the property value of an object is an object. The property name and property value in this object are the property name and property value respectively (this is not easy to understand, just look at the example ).

var book={};Object.defineProperties(book,{  _year:{    writable:true,    value:2004  },  edition:{    writable:true,    value:1  },  year:{    get:function(){      return this._year;    },    set:function(){      if(newValue>2004){        this._year=newValue;        this.edition+=newValue-2004;      }    }  }}); 

4. How to Use the Object. getOwnPropertyDescripter () method to read the attribute descriptor to read the attribute features

We can use the Object. getOwnPropertyDescripter () method to obtain the descriptor of a given attribute. GetOwnPropertyDescripter is used to get its own attribute descriptor. This method receives two parameters: the object where the attribute is located needs to read the attribute name of its descriptor. Returns an object.

For accessors, the attributes of this object include retriable, enumerable, get, and set;

For data attributes, the attributes of this object include retriable, enumerable, writable, and value.

Var book ={}; Object. defineProperties (book, {_ year :{ value: 2004}, edition: {value: 1}, year: {get: function () {return this. _ year ;}, set: function () {if (newValue> 2004) {this. _ year = newValue; this. edition + = newValue-2004; }}}); var descriptor = Object. getOwnPropertyDescriptor (book, "_ year"); console. log (descriptor. value); // 2004console. log (descriptor. resumable); // false because Object. the attributes created by the defineProperties () method are all falseconsole. log (typeof descriptor. get); // undefined Note: This is a data attribute and is var descriptor = Object without the get feature. getOwnPropertyDescriptor (book, "year"); console. log (descriptor. value); // undefinedconsole. log (descriptor. enumerable); // falseconsole. log (typeof descriptor. get); // although function get is a feature of an attribute, it is also a function

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, for more information, see the PHP Chinese website (www.php1.cn )!

Related Article

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.