Home  >  Article  >  Web Front-end  >  Detailed explanation of data attributes and accessor attributes of JavaScript objects

Detailed explanation of data attributes and accessor attributes of JavaScript objects

青灯夜游
青灯夜游forward
2020-07-09 15:00:042464browse

Detailed explanation of data attributes and accessor attributes of JavaScript objects

There are two ways to create objects: the first is through the new operator followed by the Object constructor, and the second is the object literal method. As follows

var person = new Object();
person.name = 'Nicy';
person.age = 21;
person.sayName = function() {
    console.log(this.name);
};        
var person = {
    name: 'Nicy',
    age: 21,
    sayName: function() {
        console.log(this.name);
    }
}

The objects created by these two methods are the same and have the same properties and methods. These properties have internal property descriptors that describe their behavior.

Object.defineProperty()

Through Object.defineProperty(), you can directly create a property on the object or modify the existing one. Attributes.

Object.defineProperty(obj, prop, descriptor) receives three parameters:

obj: the object where the property is located

prop: the name of the property to be accessed

Descriptor: Descriptor object

The descriptor object contains six properties: configurable, enumerable, writable, value, get, set. To modify the characteristics of the properties, you must use the Object.defineProperty() method.

The default value of the Boolean property of the object properties added through the above two methods is true. When modifying the property properties through Object.defineProperty, only set the properties that need to be modified; and through Object The property created by .defineProperty has a Boolean attribute whose default value is false.

There are two types of properties in ECMAScript: data properties and accessor properties.

Data attributes

Data attributes contain four attribute descriptors:

[[Configurable]]: Indicates whether Redefine the property by deleting it through delete. Can the property properties be modified? Can the property be modified into an accessor property? The object properties added through the above method default to true.

[[Enumerable]] : Indicates whether the property can be accessed through for-in loop. The object properties added through the above method default to true.

[[Writable]] : Indicates whether the value of the attribute can be modified. The object properties added through the above method default to true.

[[Value]]: Contains the data value of this attribute, which can be read and written. The object properties added through the above method are undefined by default.

Writable

var person = {};

Object.defineProperty(person, "name", {
    value: 'Nicy'
})
person.name = 'Lee';  
console.log(person.name)    // 'Nicy'

Object.defineProperty(person, "name", {
    writable: true
})
person.name = 'Lee';
console.log(person.name)    // 'Lee'

The property writable created directly by Object.defineProperty defaults to false, and the value cannot be modified. At this time, the name is changed to Lee. It cannot be used in non-strict mode. An error will be reported, but the operation will be ignored. In strict mode, an error will be reported.

Configurable

<span style="font-size: 13px;"><span style="color: #0000ff;"></span>var person = {<br>    name: 'Nicy',<br>    age: 21,<br>    sayName: function() {<br>        console.log(this.name);<br>    }<br>}<br><br>Object.defineProperty(person, "name", {<br>    configurable: false<br>})<br><br>delete person.name;    // 操作被忽略,无法通过delete删除属性<br>Object.defineProperty(person, "name", {    // throw error<br>    configurable:true    <br>})     <br>Object.defineProperty(person, "name", {    // throw error<br>    enumerable: false<br>})  <br>Object.defineProperty(person, "name", {     // 由于writable为true,所以可以修改value<br>    value: 'Lucy'<br>})console.log(person.name)    // Lucy<br>Object.defineProperty(person, "name", {    // writable可进行true -> false的单向修改<br>    writable: false<br>})<br>Object.defineProperty(person, "name", {     // throw error<br>    value: 'Lee'<br>})<br>Object.defineProperty(person, "name", {    // throw error,此时writable不可以false -> true<br>    writable: true<br>})<span style="color: #000000;"></span></span>

To summarize configurable: When configurable is set to false,

1. You cannot delete the attribute through delete to redefine it. Properties;

2. Cannot be converted into accessor properties;

3. Configurable and enumerable cannot be modified;

4. writable can be modified one-way to false, but cannot be changed from false to true;

5. Whether the value can be modified depends on writable.

When configurable is false, use delete to delete the attribute. In non-strict mode, no error will be reported, but the operation is ignored. In strict mode, an error will be reported; when other features that cannot be modified are modified, an error will be reported. .

Enumerable

enumerable indicates whether the object properties can be enumerated in for...in and Object.keys().

var person = {};
Object.defineProperty(person, "a", { value : 1, enumerable:true });
Object.defineProperty(person, "b", { value : 2, enumerable:false });
Object.defineProperty(person, "c", { value : 3 }); // enumerable defaults to false
person.d = 4; // 如果使用直接赋值的方式创建对象的属性,则这个属性的enumerable默认为true

for (var i in person) {    
  console.log(i);  
}  //  'a' 和 'd' 

Object.keys(person); // ["a", "d"]

Accessor properties

Accessor properties contain four property descriptors:

[[Configurable]]: Indicates whether the attribute can be redefined by deleting the attribute through delete, whether the attribute characteristics can be modified, and whether the attribute can be modified into a data attribute. Properties defined directly on the object default to true.

[[Enumerable]] : Indicates whether the property can be accessed through for-in loop. Properties defined directly on the object default to true.

[[Get]]: Function called when reading properties, default is undefined.

[[Set]]: Function called when writing properties, default is undefined.

var person = {
    name: 'Nicy',
    _age: 21,
    year: 1997,
    _year: 1997,
    sayName: function() {
        console.log(this.name);
    }
}

Object.defineProperty(person, "age", {
    get: function() {
        return this._age;
    },
    set: function(value) {
        this._age = value;
                // ...
    }
})

The accessor properties defined with Object.defineProperty() have configurable and enumerable defaults to false.

Conversion between data properties and accessor properties

##Object.getOwnPropertyDescriptor Reading properties

Use Object.getOwnPropertyDescriptor to get the property descriptor:

Object.getOwnPropertyDescriptor(obj, prop)

obj: the object where the property is located;

Prop: The name of the property to be accessed.

Data attribute-> Accessor attribute

The attribute attribute can only be one of accessor descriptor and data descriptor, for existing data When a property plus get or set is converted into an accessor property, the value and writable of its property will be discarded.

The following code converts the original data attribute year of the object into an accessor attribute:

*Note: In the get and set of the accessor attribute, this cannot be used to access The property itself, otherwise infinite recursion will occur and cause memory leaks.

// 设置get和set其中任意一个即可转换为访问器属性
Object.defineProperty(person, "year", {
    get: function() {
//        return this,year;    // error
        return this._year;    
    },
    set: function(value) {
//             this.year = value;  // error
        this._year= value;
    }
})

var descriptor = Object.getOwnPropertyDescriptor(person, 'year');
console.log(descriptor);    // {get: ƒ, set: ƒ, enumerable: true, configurable: true}
In the original data attribute year, use Object.defineProperty() to set get or set for the attribute, which can be converted into an accessor attribute.

Accessor properties -> Data properties

将访问器属性转换为数据属性,只需要给现有访问器属性设置value或writable这两个属性描述符中的任意一个即可,其原有的get和set就会被废弃,从而转换为数据属性。

上面为person定义的访问器属性age,通过Object.defineProperty()只设置了get和set,所以configurable默认为false,不可以将其转换为数据属性。可以在访问器属性和数据属性间相互转化的属性其configurable特性值必须为true。

如下代码,我们为person新定义一个访问器属性job,将其configurable设置为true ,并将其转换为数据属性:

Object.defineProperty(person, "job", {
    configurable: true,
    enumerable: true,
    get: function() {
        return this._job;
    },
    set: function(value) {
        this._job = value;
    }
})

// 设置value和writable其中任意一个即可转换为数据属性        
Object.defineProperty(person, "job", {
    value: 'worker',
    writable: true
})

var descriptor = Object.getOwnPropertyDescriptor(person, 'job');
console.log(descriptor);    // {value: "worker", writable: true, enumerable: true, configurable: true}

数据描述符value、writable 和访问器描述符get、set不能同时设置,否则会报错。

Object.defineProperties()

通过Object.defineProperties()可以一次性为对象定义多个属性。

var person = {};
Object.defineProperties(person, {
  name: {
    value: 'Nicy',
    writable: true
  },
  _age: {
    value: 21,
    enumerable: true,
    writable: true,
    configurable: true
  },
   age: {
    get: function() {
    return this._age;
    },
    set: function(value) {
    this._age = value;
    }
  }
});

 相关教程推荐:JavaScript视频教程

The above is the detailed content of Detailed explanation of data attributes and accessor attributes of JavaScript objects. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete