JavaScript notes--data properties and accessor properties

Source: Internet
Author: User

In JavaScript, the most basic way to create an object is to new an instance of the objects (), and then add properties and methods to it, the following example creates a person object that contains the property name, and the Name property has a characteristic value of "Xiaochang":

varnewObject"xiaochang"function(){    console.log("Hi, my name is "this.name);};person.say();   //Hi, my name is xiaochang

Eamascript 5 defines the various attributes that describe these attribute characteristics, including data properties and accessor properties .
Data Properties: This property contains the location of a data value that contains 4 properties that describe the behavior:
1. [[[Configurable]]: Indicates whether the property can be redefined by deleting the property, whether the attribute can be modified, or if the property can be modified to an accessor property.
2. [[Enumerable]]: Indicates whether the for-in loop can be returned.
3. [[writable]]: Indicates whether the value of the property can be modified.
4. [[Value]]: Contains the data value of this property. Read the value of the property when reading from this location, write the property value when the update to this location, the default value is undefined.

The data properties of properties defined directly on the object are defaulted as follows:
1. [[Configurable]]:true
2. [[Enumerable]]:true
3. [[Writable]]:true
4. [[value]]: "Xiaochang" (initial assignment)

These attributes cannot be accessed directly, and the attributes to be modified can only be passed the Object.defineproperty () method, which contains three parameters: the object where the property resides, the name of the property, and the Descriptor object [configurable|enumerable| Writable|value]. For example:

var person = {Age: -};object.defineproperty (Person,"Name", {configurable:false, writable:false, Value:"Xiaochang"}); Object.defineproperty (person,"Tall", {value: the}); for(attr in person) {Console.Log(attr);//name,age}console.Log(Person.name);//xiaochangPerson.name="CC";//Specify a new value for the Name propertyConsole.Log(Person.name);//xiaochangDeletePerson.name;//Remove the Name propertyConsole.Log(Person.name);//xiaochangConsole.Log(Person.age);//100Person.age= $;//Specify a new value for the Age propertyConsole.Log(Person.age);//200DeletePerson.age;//Delete Age PropertyConsole.Log(Person.age);//undefinedConsole.Log(Person.tall);//160Person.tall = the;//Modify the value of the Tall propertyConsole.Log(Person.tall);//160DeletePerson.tall;//Remove the Name propertyConsole.Log(Person.tall);//160

The analysis example shows that properties defined directly on the object, such as age,[[configurable]],[[enumerable]],[[writable]], are set to true.
The [[configurable]],[[writable]] property name is set to False, so it cannot be modified or deleted.
When you call the Object.defineproperty () method, the default is False if you do not display the value of the specified configurable,enumerable,writable, such as the property tall.
It is also important to note that when configurable is set to false, it cannot be changed to true, and other attributes cannot be modified except for writable. You can modify the same property multiple times by calling Object.defineproperty () in case configurable is true.
Modifying a property operation that cannot be configured under strict conditions is ignored and throws an error in strict mode.

Accessor Properties : Contains getter and setter functions. When the accessor property is read, the Getter function is called to return a valid value, and when the accessor property is written, the setter function is called to pass in the new value. It contains 4 features:
1. [[[Configurable]]: Indicates whether the property can be redefined by deleting the property, whether the attribute can be modified, or if the property can be modified to an accessor property.
2. [[Enumerable]]: Indicates whether the for-in loop can be returned.
3. [[Get]]: The function that is called when the property is read, the default undefined.
4. [[Set]]: The function that is called when the property is written, the default undefined.

Getter and setter do not have to appear in pairs, only the Getter function proves that the property is read-only and not writable, the attempt to write is ignored in non-strict mode, and strict mode throws an error. Similarly, only the setter function proves that write-only unreadable, attempts to read in non-strict mode to return undefined, strict mode throws an error.

Accessor properties cannot be defined directly and must be defined using Object.defineproperty (), as follows:

varperson = {_name:"Xiaochang",//name property is read-only and not writable_age: -,//age property is write-only and unreadable_tel:123456      //tel Property readable and writable};object.defineproperty (Person,"Name",{Get: function(){        return  This. _name; }}); Object.defineproperty (person,"Age",{Set: function(newage){         This. _age = NewAge; }}); Object.defineproperty (person,"Tel",{Get: function(){        return  This. _tel; },Set: function(NewTel){         This. _tel= NewTel; }}); Console.log (Person.name);//"Xiaochang"Person.name ="CC";//Try to modify the Name propertyConsole.log (Person.name);//"Xiaochang"Console.log (Person.age);//non-readable properties, undefinedPerson.age = $;//Modify AgeConsole.log (Person._age);///Direct Read object method to access the property, you can see that the value has been updatedConsole.log (Person.tel);//123456Person.age =654321;//Update TelConsole.log (Person.tel);//654321

The underscore in front of the property represents a property that can only be accessed through an object method, and when we call Person.name the Getter function that actually calls the Name property (calling Person._name directly can get the same result, making the accessor meaningless). The relationship between attributes and accessors can be clearly seen in the example above.

Browsers that support the Object.defineproperty () method have ie9+ (IE8 is the first browser that implements the Object.defineproperty () method, but is limited to DOM objects and can only create accessor properties), firefox4+, safari5+,opera12+, Chrome. [[configurable]],[[enumerable]] cannot be modified in browsers that do not support the Object.defineproperty () method.

Before the Object.defineproperty () method, to create accessor properties, general use of non-standard methods: __defineGetter__() and __defineSetter__() , these two methods were originally introduced in Firefox, and later Chrome1 and Opera9.5 also support. Overwrite the above Tel property accessors as follows:

person.__defineGetter__("tel",function(){    returnthis._tel;});person.__defineSetter__("tel",function(newtel){    this._tel = newtel;});

ECMAScript 5 also defines the Object.defineproperties () method, which contains two parameters: the object where the property resides, the name of multiple properties, and the object that consists of its descriptor object. It acts on the same object.defineproperty (), and the difference is that it can be fixed to multiple properties at once. Browsers that support this approach are ie9+, firefox4+, safari5+,opera12+, and Chrome. The above example can be rewritten as follows:

varperson = {_name:"Xiaochang",//name property is read-only and not writable_age: -,//age property is write-only and unreadable_tel:123456      //tel Property readable and writable};object.defineproperties (person,{name:{Get: function(){            return  This. _name; }}, age:{Set: function(newage){             This. _age = NewAge; }}, tel:{Get: function(){            return  This. _tel; },Set: function(NewTel){             This. _tel= NewTel; }    }});

For the attribute attributes described above, ECMAScript 5 gives a method Object.getownpropertydescriptor () that can obtain a descriptor for a given property, which contains two parameters: the object where the property resides, and the name of the property whose descriptor is to be read. method returns an object. For the example above, you can:

var descriptor = Object.getOwnPropertyDescriptor(person,"tel");forin descriptor ){    console.log(attr+":"+descriptor[attr]);}运行结果如下:get:function (){returnthis._tel;}set:function (newtel){this._tel= newtel;}enumerable:falseconfigurable:false

JavaScript notes--data properties and accessor properties

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.