Deep understanding of properties and features in JavaScript

Source: Internet
Author: User

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:

    • Understand the nature of objects in JavaScript, 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, 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

123456789         varperson={};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

1234567         varperson={};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

12345678 varperson={};Object.defineProperty(person,"name",{    value:"zhuzhenwei",    configurable:false});console.log(person.name);//zhuzhenweideleteperson.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

12345678 varperson={};Object.defineProperty(person,"name",{    value:"zhuzhenwei",    configurable:true});console.log(person.name);//zhuzhenweideleteperson.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

1234567891011   &nbs p;      var   person={}; Object.defineproperty (person, "name" , {      Value: "Zhuzhenwei" ,      Configurable: false }); Console.log (person.name); //zhuzhenwei Object.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

1234567891011 console.log (pers On.name); //uncaught Typeerror:cannot redefine property:name (...) var   person={}; Object.defineproperty (person, "name" , {      Value: "Zhuzhenwei" , }); Console.log (person.name); //zhuzhenwei Object.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:

12345678910111213141516 varbook={    _year:2004,    edition:1};Object.defineProperty(book,"year",{    get:function(){<br>            returnthis._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.
      1
    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 ).

12345678910111213141516171819202122 varbook={};Object.defineProperties(book,{    _year:{        writable:true        value:2004    },    edition:{        writable:true,        value:1    },    year:{        get:function(){            returnthis._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.

varbook={};Object.defineProperties(book,{    _year:{        value:2004    },    edition:{        value:1    },    year:{        get:function(){            returnthis._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  因为通过Object.defineProperties()方法创建的属性的特性configurable enumerable都是falseconsole.log(typeofdescriptor.get);//undefined 注意:这是数据属性,是不具有get特性的vardescriptor=Object.getOwnPropertyDescriptor(book,"year");console.log(descriptor.value);//undefinedconsole.log(descriptor.enumerable);//falseconsole.log(typeofdescriptor.get);//function get虽然是属性的一个特性,但是它也是函数。

  

Click here to return to the top page

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

Deep understanding of properties and features in JavaScript

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.