Deep understanding of properties and features in JavaScript

Source: Internet
Author: User

deep understanding of properties and features in JavaScript

The properties and attributes in JavaScript are two completely different concepts, and i'll take a closer look at the properties and features in javascript, based on what I've Learned.

 The main contents are as Follows:

    • Understanding the nature of objects in javascript, understanding the relationship between objects and classes, and the relationship between objects and reference types
    • How object properties are categorized
    • Understanding of attributes in a property

Part I: Understanding the nature of objects in javascript, understanding the relationship between objects and classes, and the relationship between objects and reference types

The essence of an object:ECMA-262 defines an object as a collection of unordered properties whose properties can contain basic values, objects, or functions . That is, an object is a set of values that have no specific order, and each property or method of an object has a name that maps to a Value. The essence of an object is a hash table: a set of Name-value pairs, which can be data or functions.

Relationships between objects and Classes: in javascript, objects and classes have no relationship . This is because there is no concept of class in ecmascript, and its objects are different from those in other class-based languages .

  Object and reference type Relationships: objects and reference types are not equivalent because each object is created from a reference type .

part Ii: How object properties are categorized

Objects created by constructors or object literal methods have properties and methods (as long as they refer to properties and methods, they must belong to the object; as long as the object is mentioned, it must be a property and a method (except for customization), where the attributes can be divided into data properties and accessor properties, and their differences are as follows:

    • Data properties are typically used to store data values, and accessor properties do not contain a data value
    • Accessor properties are used for get/set operations

part Iii: understanding of attributes in Properties

ECMAScript defines the concept of attributes (attribute) in order to describe the various characteristics of object Properties. That is, attributes are different from attributes, and attributes are used to describe properties. below, I will explain separately:

    • Data properties and their characteristics
    • accessor properties and their attributes
    • How to define multiple attributes using the Object.defineproperties () method
    • How to use the Object.getownpropertydescripter () method to read a Property's descriptor to read the attributes of a property

1. Data attributes and their characteristics

  As we've just said, data properties are used to store data values, so the Data property has a location for the data value, where the value can be read and Written. The data attribute has 4 attributes that describe its behavior, because ECMAScript rules that the attribute cannot be accessed directly in JavaScript (note: not inaccessible), so we put it in two sets of square brackets. As follows:

    • [[[configurable]]: The default value is true,a, indicating whether the Delete property can be removed by deleting to redefine the property b, can modify the Property's attribute c, the ability to modify the property from the data property to the accessor property
    • [[[Enumerable]]: The default value is true, indicating whether the property can be returned through a for-in loop (so: if false, the for-in loop cannot enumerate the property it is In)
    • [[[writable]]: The default value is true, which indicates whether the value of the property can be modified, which differs from [[configurable]].
    • [[value]]: The default value is undefined, which is the attribute value of the property, we can read the property value at this location, you can also write the property value at this Location.
    • Note: The default above refers to properties owned by objects created by constructors or object literals, rather than the Object.defineproperty () method described below

These attributes all have default values, but what if these defaults are not what we want? Of course It's a change! We can use the Object.defineproperty () method to modify the Property's default Attributes. The English difineproperty is defined as the meaning of the Attribute. This method receives three parameters: the object where the property resides, the name of the property, and a descriptor Object. where the third parameter descriptor object is created by the method of the object literal, the attributes and property values inside are actually saved with the attributes and attribute values to be modified.

Here are a few examples for a deeper 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 the method and the property at the same time. instead, the Object.defineproperty () method was used to create the properties and modify the default Values. This sets the writable to false, which is not valid 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

  Pay attention to this example, I deleted the writable:false in this example, why still can not modify it? This is because the first three defaults to ture when I introduced the feature, which is obtained with the creation of the object and the creation of the Property. For properties created by calling the Object.defineproperty () method, The default value for the first three attributes is false, which you need to be aware of.

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 properties of the new property name to configurable:false, so the operation to delete the property below is not valid. According to b, configurable, the default is false, even if the removal can not be modified.

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 change the default value of configurable by the default of false to true, so it becomes configurable, then finally successfully deleted.

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 been set to false, then it is futile to change it back to true, namely: once the property is set to be non-configurable, it can no longer be reconfigured.

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 explained here that even if we ignore the default Configurable:false in the previous step, what we get later is still not configurable. As a result, it can be concluded that, in order to be configurable, the default value must be modified to True when the Object.defineproperty () function is called for the first Time.

2. accessor properties and their properties

As mentioned earlier, accessor properties do not contain data values, they contain a pair of getter functions and setter functions (these two functions are not required). When the accessor property is read, The Getter function is called, which is responsible for returning a valid value, and in writing the accessor property is invoking the setter function and passing in the new value, which is responsible for deciding what to do with the Data. similarly, because the attributes of the accessor attribute cannot be accessed directly through javascript, the attributes listed below will be enclosed in [[]] for Differentiation.

    • [[[configurable]]: The default value is true,a, indicating whether the Delete property can be removed by deleting to redefine the property b, can modify the Property's attribute c, the ability to modify the property from the accessor property to the Data property
    • [[[Enumerable]]: The default value is true, indicating whether the property can be returned through a for-in loop (so: if false, the for-in loop cannot enumerate the property it is In)
    • [[Get]]: the function that is called when the property is read . The default value is undefined key: the attribute can be a function
    • [[Set]]: the function that is called when the property is written . The default value is undefined key: the attribute can be a function because the get and set functions also belong to attributes, Then they are likely to (say it is possible because both functions are not required) appear in the properties of the third parameter descriptor object in Object.defineproperty.

Note: 1. In relation to the data properties, we find that the accessor attribute does not have the writable attribute and the value Attribute. this is because the accessor property does not contain a data value , then of course we cannot modify the value of the property (not using the writable attribute), let's not consider Value.

2. accessor properties cannot be defined directly and must be defined with Object.defineproperty (). ( with this rule we can accurately determine the accessor attributes and data attributes. )

Use the following example to gain a deeper 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

  

Several areas that need to be understood in Depth:

    1. Accessor properties cannot be defined directly, must be defined using Object.defineproperty (), and the property has set and Ger attributes, so you can tell that _year and edition are data properties, and year is an accessor Property.
    2. We see _year. this data property is preceded by an _ (underscore), a common notation used to represent properties that can be accessed only through object methods. from the example above you can see a method of get equivalent to a descriptor object , and _year is the property that is accessed in this object method. The edition can be accessed either through the object method or directly by the Object.
    3. Book.year indicates that the accessor property is being read, and the Get function is called and returns a valid value of 2004.
    4. BOOK.YEAR=2005 represents the write accessor property , which invokes the set function and passes in the new value, passing 2005 to newvalue, which determines how the data is Processed.
    5. A common way to use accessor properties at this point is to set the value of one property to cause other properties to Change.

3. How to define multiple attributes using the Object.defineproperties () method

obviously, An object cannot have only one property, so it is possible to define multiple properties, so JavaScript provides the Object.defineproperties () method to solve the Problem. This method takes two parameters, the first is to define the object where the property is located, the second is an object literal method created object, the Object's property name is the special name to be defined, the Object's property value is an object, the property name and property values in this object are the attribute name and attribute value respectively ( This is not a good understanding, just look at examples ).

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 Property's descriptor to read the Attribute's properties

  We can use the Object.getownpropertydescripter () method to get a descriptor for a given Property. Getownpropertydescripter is the meaning of obtaining the descriptor of its own Property. This method receives two parameters: the object whose property contains the property name to read its Descriptor. Returns an Object.

For accessor properties, The properties of this object are configurable, enumerable, get, and set;

For data properties, The properties of this object are configurable, 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.configurable)//false because of the  properties of the property created by the Object.defineproperties () method configurable Enumerable are Falseconsole.log (typeof descriptor.get);//undefined note: This is a data property and is a var with no get attribute descriptor= Object.getownpropertydescriptor (book, "year"); Console.log (descriptor.value);//undefinedconsole.log ( Descriptor.enumerable);//falseconsole.log (typeof descriptor.get);//function Get is an attribute of a property, but it is also a function.

  

Click here to return to the top page

to the extent that most people work hard, it is impossible to spell Talent.

In-depth understanding of properties and features in JavaScript

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.