On the data attribute, accessor property and Object.defineproperty method of JS Object

Source: Internet
Author: User

First, the object

Needless to say, there are several common ways to create objects:

  1. Create the object from the constructor, as follows:

function Person () {        varnew person ();

2. Create a simple object by using object, for example:

var New Object ();

3. Create objects by literal.

var obj = {};

Commonly used are the first and third methods.

Second, the attribute type

  There are two types of properties in JavaScript: Data properties and accessor properties, which are specifically used to describe the various characteristics of an object's properties, such as whether the value of the object's properties can be changed, because these attributes are intrinsic values, and JavaScript is not directly accessible. So in the specification they were placed in two pairs of retroflex suffixation brackets, for example [[Enumerable]]. Here's a look at both of these specific internal properties.

1. Data properties

The Data property contains a data value. In this position, you can read and write values,

[[[Configurable]]: Indicates whether the property can be redefined by deleting the attribute, whether the attribute can be modified, whether the property can be modified to the accessor property (this is said later), and the default is true;

[[Enumerable]]: An enumeration attribute used to decorate an object's properties, indicating whether the property is returned by using a for in loop, which is true by default;

[[[Writable]]: Used to decorate the object property value of the Writable property, the default is true;

[[Value]]: Contains the data value of this property, the accessor attribute does not have this feature. The default is undefined, such as var person = {Name: ' Lili '}, where a property named name is set, its value is "Lili", the [[Value]] attribute is set to "Lili", and the remaining three attributes are the default value TRUE.

Here is a concrete example to understand the above features. First of all, here is the Object.defineproperty () method, which takes three parameters: the object where the property is located, the name of the property, and a descriptor object (that is, the four data attributes above, which describes the properties of the object), which isto be noted, When creating an attribute using the Object.defineproperty method, the Data property [[[Configurable]], [[Writable], [[Enumerable]] defaults to false, which is the opposite of the default when you declare a property directly with the literal , But if you just change the value of an existing attribute with Object.defineproperty, there is no such limit, see the following example:

var person = {};
Object.defineproperty (person, ' name ', {///create name attribute value:' Lili ', }) ; // Lili Person.name = ' Shasha ';//writable default is False property value not changed //Lili

Modify the value of writable to true to see that the value of Person.name prints out is ' Shasha ';

var person = {};object.defineproperty (person,' name ', {//Create Name Property            writable:True  ,            value:' Lili ',        });         // Lili        // writable set to true, property values are overridden        // Shasha

But when the person has attributes, the default value is True when the Object.defineproperty method only modifies the attributes and values, see the following example:

    var person = {age:22};        Object.defineproperty (person,' age ', {  /// Redefine Modify Age property            value:33,        });         =N/        A; // The  writable indicates that this is true at this time,

The rule setting the [[enumrable]] attribute is the same as [[writable]], which is true in order to iterate through the property with the for In loop. Here's a look at the role of [[configurable]] features, as in the following example:

   var person = {};        Object.defineproperty (person,' name ', {            configurable:false,            value:' Lili ') ,        });         // Lili        Delete person.name;         // Lili

Setting configurable to False means that object properties cannot be deleted, the Delete method is called on this property, nothing happens in strict mode, an error is thrown when the property is set to false from configurable , it cannot be set to true at this point, when calling the Object.defineproperty method to modify an attribute other than writable, value, will result in an error, see the following example:

   varperson = {}; Object.defineproperty (person,' Name ', {configurable:false, Enumerable:true, writable:true, Value:' Lili ',        }); Object.defineproperty (person,' Name ', {            //configurable:true,//Will error the amount!            //Enumerable:false,//Will be an error!Writable:false, Value:' Tangtang ',        }); Person.name= ' Wangdachui '; Console.log (person.name);//tangtang

2. Accessor Properties

The accessor property does not include a data value, which contains a pair of getter and setter functions, and when the accessor property is read, the Getter function is called, which is responsible for returning a valid value, and when the accessor property is written, the setter function is called and the new value is passed, and the accessor property has the following four attributes:

[[[Configurable]]: Indicates whether the property can be redefined by deleting the attribute, whether the attribute can be modified, whether the property can be modified to a data property (this is said later), and the default is true;

[[Enumerable]]: An enumeration attribute used to decorate an object's properties, indicating whether the property is returned by using a for in loop, which is true by default;

[[Get]]: The function that is called when the property is read, the default is Undeifne;

[[Set]]: The function that is called when writing the property, the default is Undeifne;

Accessor properties cannot be defined directly and must be defined using Object.defineproperty (). Take a look at the example below.

   varBook ={_year:2018, Edition:1,        }; Object.defineproperty (book,' Year ', {get:function() {alert (' Access by object method haha! ‘); return  This. _year; }, set:function(newvalue) {if(NewValue > 2004) {                     This. _year =NewValue;  This. edition + = newValue-2004; Alert ( This. Edition);        }            }        }); Console.log (book.year)//access to the Get function through the object method to the alert out the corresponding information;Book.year = 2005; Console.log (book.edition); 2

In the example above, the book object has two default properties: _year and edition, where _year is preceded by an underscore to indicate that the property can only be accessed through an object method, that is, the property value is returned through the Get method. If the value of book.edition is accessed directly, the Get method is not called to return. Book.year=2005 is to modify the book's Year property value, call the Set method, the parameter newvalue is the set 2005 value, in the above example, the SET function also changed the value of the property edition.

3. Define multiple properties

With Object.defineproperties We can also define multiple properties for an object, this method has two parameters: the first object to define the property, the second is the object, the number of properties to add and its corresponding property descriptor, how to add it, see the following example:

   varBook = {}; Object.defineproperties (book,{_year:{writable:true, Value:2004,}, edition:{writable:true, Value:1,}, year:{get:function(){                    return  This. _year; }, set:function(newvalue) {if(NewValue > 2004){                         This. _year =NewValue;  This. edition + = newValue-2004; }                }            }        });

The above code defines two data attributes (_year and edition) and one accessor property (year) on the book object.

4. Properties of the Read attribute

We've been talking about how to set property description properties, so how do we read the specifics of the data properties and accessor properties? Here is another method of object: The Getownpropertydescriptor method, which receives two parameters: the object where the property resides and the name of the property whose descriptor is to be read, and its return is an object, let's look at a specific instance:

  varBook = {}; Object.defineproperties (book, {_year: {writable:true, Value:2004,}, Edition: {writable:true, Value:1,}, 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        varDescriptor1 = Object.getownpropertydescriptor (book, ' _year ')); Console.log (Descriptor1.value); //2005Console.log (descriptor1.configurable);//falseConsole.log (typeofDescriptor1.get);//undefine        varDescriptor2 = Object.getownpropertydescriptor (book, ' Year '); Console.log (Descriptor2.value); //2005Console.log (descriptor2.configurable);//falseConsole.log (typeofDescriptor2.get);//function;

  

  

  

  

  

On the data attribute, accessor property and Object.defineproperty method of JS Object

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.