JavaScript Object.defineproperty ()

Source: Internet
Author: User
Tags array length

Object.defineproperty ()

tags (space delimited): JavaScript

Original address
Source Address

Object.defineProperty()Method defines a new property directly on an object, or modifies an existing property of an object and returns the object.

First, the grammar

Object.defineproperty (obj, prop, descriptor)

    1. Parameters

      objThe object on which to define the property.

      propThe name of the property to be defined or modified.

      descriptorThe property descriptor that will be defined or modified.

    2. return value

      The object that is passed to the function.

Ii. description

The change method allows you to precisely add or modify the properties of an object. Ordinary properties added by assignment create properties (or methods) that are displayed during property enumeration for...in , which Object.keys can be changed or deleted. This release allows these additional details to be changed from the default value. By default, the Object.defineProperty() value of the property that is added is immutable.

There are two main forms of attribute descriptors present in objects: data descriptors and access descriptors. A data descriptor is a property with a value that is writable or may not be writable. The accessor descriptor is a property described by the Getter-setter function pair. Descriptors must be one of these two forms;

Both the data descriptor and the access descriptor have the following optional key values:

configurable
When and only if the property's configurable bit is true, the property describes that the characters can be changed and that the property can be deleted from the corresponding object. The default is Flase.

enumerable
This property can appear in the object's enumeration property only if and only if the property's enumerable is true. The default is False.

The data descriptor has the following optional key values:

value
The value that corresponds to the property. Can be any valid JS value (numeric, object, function, etc.). The default is undefined.

writable
This property can be changed by the assignment operator only if and only if the property's writable is true. The default is False.

The access descriptor also has the following optional key values:

get
A method that provides a getter to a property, or undefined if no getter is available. The method return value is used as the property value. The default is undefined.

set
A method that provides a setter to a property without a setter without a undefined. The method will accept the unique parameter and assign the new value of the parameter to the property. The default is undefined.

These options are not necessarily self-attributes and should be considered if they are inherited. To confirm that these default values are retained, you may want to freeze before this Object.prototype , explicitly specifying all options, or __proto__ pointing the property to null.

// 使用 __proto__var obj = {};var descriptor = Object.create(null); // 没有继承的属性// 默认没有 enumerable,没有 configurable,没有 writabledescriptor.value = ‘static‘;Object.defineProperty(obj, ‘key‘, descriptor);// 显示Object.defineProperty(obj, ‘key‘, {    enumerable: false,    configurable: false,    writable: false,    value: ‘static‘});// 循环使用同一对象function withValue(value) {    var d = withValue.d || (        withValue.d = {            enumerable: false,            writable: false,            configurable: false,            value: null        }    );    d.value = value;    return d;}// ... 并且 ...Object.defineProperty(obj, ‘key‘, withValue(‘static‘));// 如果 freeze 可用,防止代码添加或删除对象原型的属性// (value,get,set,enumerable,writable,configurable)(Object.freeze || Object)(Object.prototype);
Iii. examples
    1. Creating properties

If the specified attribute does not exist in the object, Object.defineProperty() this property is created. When some fields are omitted from the descriptor, these fields will use their default values. The default value for a field that has a Boolean value is false.

value, get and set The default value for the field is undefined . A property that is not get/set/value/writable defined is called "generic" and is "typed" as a data descriptor.

var o = {}; // 创建一个新对象// 在对象中添加一个属性与数据描述符的示例Object.defineProperty(o, ‘a‘, {    value: 37,    writable: true,    enumerable: true,    configurable: true});// 对象o拥有了属性a,值为37// 在对象中添加一个属性与存取描述符的示例var bValue;Object.defineProperty(o, ‘b‘, {    get: function () {        return bValue;    },    set: function (v) {        bValue = v;    },    enumerable: true,    configurable: true});o.b = 38;// 对象b拥有了属性b,值为38// o.b的值现在总是与bValue相同,除非重新定义o.b// 数据描述符和存取描述符混合使用Object.defineProperty(o, ‘conflict‘, {    value: 0x9f91102,    get: function () {        return 0xdeadbeef;    }});// 抛出错误: value appears only in data descriptors, get appears only in accessor descriptors// value只出现在数据描述符中,get只出现在访问符描述符中
    1. modifying properties

If the property already exists, Object.defineProperty() it will attempt to modify the property based on the value in the descriptor and the current configuration of the object. If the old descriptor sets its configurable property to false , the property is considered "not configurable" and no property can be changed back (except for one-way change writable to false). When a property is not configurable, you cannot switch between data and accessor property types.

writable{jsxref ("TypeError")}} will be thrown when the view changes the value of the non-configurable property (except for the attribute), unless the current value and the new value are the same.

Writable Property

When writable the property is set to false , the property is called "Not writable." It cannot be reassigned.

// Writable 属性var ob = {}; // Create a new objectObject.defineProperty(ob, ‘a‘, {    value: 37,    writable: false});console.log(ob.a); // 37ob.a = 25; // 没有错误抛出console.log(ob.a); // 37// strict mode 严格模式(function () {    ‘use strict‘;    var o = {};    Object.defineProperty(o, ‘b‘, {        value: 2,        writable: false    });    o.b = 3; // 抛出类型错误:‘b‘ is read-only    return o.b; // 返回2没有上面的行})();

Enumerable characteristics

enumerableDefines whether an object's properties can be for...in enumerated in loops and Object.keys() in.

var o2 = {};Object.defineProperty(o2, ‘a‘, { value: 1, enumerable: true });Object.defineProperty(o2, ‘b‘, { value: 2, enumerable: false });Object.defineProperty(o2, ‘c‘, { value: 3 }); // emumerable默认为falseo2.d = 4; // 如果直接赋值创建对象的属性 默认为truefor (var i in o2) {    console.log(i);    // 打印 ‘a‘ ‘d‘}var o2a = o2.propertyIsEnumerable(‘a‘); // truevar o2b = o2.propertyIsEnumerable(‘b‘); // falsevar o2c = o2.propertyIsEnumerable(‘c‘); // falseconsole.log(o2a, o2b, o2c);

Configurable characteristics

configurableAttributes indicate whether an object's properties can be deleted back, and writable whether other attributes other than attributes can be modified.

var o3 = {};Object.defineProperty(o3, ‘a‘, {    get: function () { return 1; },    configurable: false});Object.defineProperty(o3, ‘a‘, {    configurable: true});// Uncaught TypeError: Cannot redefine property: aObject.defineProperty(o3, ‘a‘, {    enumerable: true});// Uncaught TypeError: Cannot redefine property: aObject.defineProperty(o3, ‘a‘, {    set: function (v) { }});// Uncaught TypeError: Cannot redefine property: aObject.defineProperty(o3, ‘a‘, {    get: function () { return 1; }});// Uncaught TypeError: Cannot redefine property: aObject.defineProperty(o3, ‘a‘, {    value: 12});// Uncaught TypeError: Cannot redefine property: aObject.defineProperty(o3, ‘a‘, {    writable: true});// Uncaught TypeError: Cannot redefine property: aconsole.log(o3.a); // 1delete o3.a;console.log(o3.a); // 1

If o.a the configurable property is true , no error will be thrown, and the property will be deleted at the end.

Add multiple properties and default values

It is important to consider the default attribute values that are assigned to attributes, typically when you use the dot operator and Object.defineProperty() assign a value to an object's properties. The default value of the property in the data descriptor is different, as shown in the following example.

var o4 = {};o4.a = 1;// 等同于:Object.defineProperty(o4, ‘a‘, {    value: 1,    writable: true,    configurable: true,    enumerable: true});// 另一方面Object.defineProperty(o4, ‘b‘, { value: 1 });// 等同于Object.defineProperty(o, ‘b‘, {    value: 1,    writable: false,    configurable: false,    enumerable: false});

The General setters and getters

The following example shows how to implement a self-archiving object. When temperature the property is set, the archive array gets the log entry.

  function Archiver () {var temperature = null;        var archive = [];            Object.defineproperty (this, ' temperature ', {get:function () {console.log (' get ... ');        return temperature;            }, Set:function (v) {temperature = V;        Archive.push ({val:temperature});        }    });        this.getarchive = function () {Console.log (archive);    return archive; }}var arc = new Archiver (); arc.temperature; Get...arc.temperature = 11;arc.temperature = 12;arc.getarchive (); [{val:11}, {val:12}]  
var pattern = {    get: function () {        return ‘I alway return this string, whatever u have assigned.‘;    },    set: function () {        this.myname = ‘This is my name string.‘;    }};function TestDefineSetAndGet() {    Object.defineProperty(this, ‘myproperty‘, pattern);}var instance = new TestDefineSetAndGet();instance.myproperty = ‘test‘;console.log(instance.myproperty); // I alway return this string, whatever u have assigned.console.log(instance.myname); // This is my name string.
Iv. compatibility

Desktop

| Chrome | Edge | Firefox | IE | Opera | Safari |
|: ----- |: ----- |: ----- |: ----- |: ----- |: ----- |
| 5 | Yes | 4 | + + | 11.6 | 5.12 |

Mobile

| Android WebView | Chrome for Android | Edge Mobile | Firefox for Android | IE Mobile | Opera Android | IOS Safari |
|: ----- |: ----- |: ----- |: ----- |: ----- |: ----- |: ----- |
| Yes | Yes | Yes | 4 | Yes | 11.5 | Yes |

Redefine the length property of an Array object

The redefinition of the length property of an array object is fully supported only in Internet Explorer 9 and later versions and in Firefox 23 and later versions. Currently, do not rely on redefining the array length property to work, or to work in a specific situation. At the same time, even if you can rely on it, you don't have the right reason to do so.

Internet Explorer 8 Specific cases

Internet Explorer 8 implements the Object.defineproperty () method, but can only be used on DOM objects. Some things to be aware of:

  • Attempts to use on native objects Object.defineProperty() will give an error.
  • The property attribute must have some specific values set. For Data property descriptors, the attribute must all be set to, for the configurable enumerable writable true Accessor Property descriptor, must configurable true enumerable be set to false . Any view that provides additional values will cause an error to be thrown.
  • Reconfiguring a property first requires removing the property. If the property is not deleted, it is like an attempt before reconfiguring.

Last updated By:jehorn, Dec, 09:59 AM

JavaScript Object.defineproperty ()

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.