Detailed description of attribute descriptors in ECMAScript 5 and ecmascript

Source: Internet
Author: User

Detailed description of attribute descriptors in ECMAScript 5 and ecmascript

Attribute descriptor is a new concept in es5. its function is to add more control over the attributes of an object.

Object. defineProperty

To study attribute descriptors, first talk about the Object. defineProperty method. This method defines new attributes for the object or modifies existing attributes. The prototype is as follows:
Copy codeThe Code is as follows:
Object. defineProperty (obj, prop, descriptor)

Example:
Copy codeThe Code is as follows:
Var obj = {};
Object. defineProperty (obj, 'attr', {value: 1 });

The above Code adds an attribute named attr to the obj object, and the value is 1. Equivalent:
Copy codeThe Code is as follows:
Var obj = {};
Obj. attr = 1;

In comparison, the Object. defineProperty syntax seems more complex. However, its biggest mystery lies in its third parameter.

Data Descriptor

Suppose we want attr to be a read-only attribute, we can add writable data descriptor:
Copy codeThe Code is as follows:
Var obj = {};
Object. defineProperty (obj, 'attr ',{
Value: 1,
Writable: false
});
Console. log (obj. attr );
Obj. attr = 2; // fail
Console. log (obj. attr );

After executing the above program, we can find that the attr value printed twice is 1, that is, writing to the attribute fails. However, this result may be a bit confusing, because the execution of the value assignment statement is not abnormal, but fails. Imagine if such a problem occurs in a large piece of code, it will be hard to find out. In fact, as long as the code runs in strict mode, exceptions will occur:
Copy codeThe Code is as follows:
'Use strict '; // enter the strict Mode
Var obj = {};
Object. defineProperty (obj, 'attr ',{
Value: 1,
Writable: false
});
Obj. attr = 2; // throw exception

Next let's take a look at another data descriptor enumerable, which can control whether the attribute can be enumerated. If you simply define an attribute, it can be enumerated in the for... in loop:
Copy codeThe Code is as follows:
Var obj = {};
Obj. attr = 1;
For (var I in obj) {console. log (obj [I]);}
Enumerable can "hide" it:

Var obj = {};
Object. defineProperty (obj, 'attr ',{
Value: 1,
Enumerable: false
});
For (var I in obj) {console. log (obj [I]);}

After executing the above Code, you will find that nothing is output on the console, because the attr attribute cannot be enumerated.

At this point, you may have a question: can the attribute descriptor be modified? For example, can a read-only attribute be defined as Writable? In fact, this depends on another data descriptor retriable, which can control whether the attribute descriptor can be changed.
Copy codeThe Code is as follows:
Var obj = {};
Object. defineProperty (obj, 'attr ',{
Value: 1,
Writable: false,
Retriable: true
});
Object. defineProperty (obj, 'attr ',{
Writable: true
});
Obj. attr = 2;

The above code first defines attr as a read-only attribute, and then defines it as writable. Therefore, the write to attr is successful.

Access Descriptor

The access descriptor is similar to the get/set accesser In the object-oriented method.
Copy codeThe Code is as follows:
Var obj = {};
Object. defineProperty (obj, 'attr ',{
Set: function (val) {this. _ attr = Math. max (0, val );},
Get: function () {return this. _ attr ;}
});
Obj. attr =-1;
Console. log (obj. attr); // 0

In the above Code, access to attr actually becomes access to _ attr, And the set function limits the minimum value to 0.

Get attribute Descriptor

As described above, we have set attribute descriptors. How can we get the configured descriptors? Object. getOwnPropertyDescriptor can complete this task.
Copy codeThe Code is as follows:
Var obj = {};
Object. defineProperty (obj, 'attr ',{
Value: 1,
Writable: false,
Retriable: true
});
Var desc = Object. getOwnPropertyDescriptor (obj, 'attr ');
Console. dir (desc );

Object Control

The Object. defineProperty mentioned above operates on the attributes of the Object, while the three methods described below operate on the Object directly.

Object. preventExtensionsThe object cannot have new attributes:
Copy codeThe Code is as follows:
Var obj = {};
Obj. attr = 1;
Object. preventExtensions (obj );
Obj. attr2 = 2; // fail

Object. sealOnly the attribute values of an object can be modified. (If the attribute is read-only, the attribute values cannot be modified ):
Copy codeThe Code is as follows:
Var obj = {};
Obj. attr = 1;
Object. seal (obj );
Obj. attr = 1.5;
Delete obj. attr; // fail

Object. freezeThe object cannot be modified at all:
Copy codeThe Code is as follows:
Var obj = {};
Obj. attr = 1;
Object. freeze (obj );
Obj. attr= 1.5; // fail
Obj. attr2 = 2; // fail

Then you may ask, how do you know if an object has been preventExtensions, seal, or freeze? The answer is to call Object. isExtensible, Object. isSealed, and Object. isFrozen respectively. The usage of these three functions is simple and it is no longer cumbersome.

In general, attribute descriptors can further strictly control objects and enhance the rigor of program logic. The only drawback is that ES5 is basically implemented in IE9 (IE9 does not support strict mode ), considering that the domestic Internet Explorer 8 shares are still relatively high, this set of things can only be used in mobile browsers and Node. js is used.

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.