


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}
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

In PHP, an array is an ordered sequence, and elements are accessed by index; an object is an entity with properties and methods, created through the new keyword. Array access is via index, object access is via properties/methods. Array values are passed and object references are passed.

PHP functions can encapsulate data into a custom structure by returning an object using a return statement followed by an object instance. Syntax: functionget_object():object{}. This allows creating objects with custom properties and methods and processing data in the form of objects.

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.

The Request object in PHP is an object used to handle HTTP requests sent by the client to the server. Through the Request object, we can obtain the client's request information, such as request method, request header information, request parameters, etc., so as to process and respond to the request. In PHP, you can use global variables such as $_REQUEST, $_GET, $_POST, etc. to obtain requested information, but these variables are not objects, but arrays. In order to process request information more flexibly and conveniently, you can
