JavaScript object-oriented detailed analysis of property descriptors
This article brings you relevant knowledge about javascript, which mainly introduces related issues about object-oriented, including attribute descriptors, data descriptors, access descriptors, etc. Let’s take a look at the content below. I hope it will be helpful to everyone.
[Related recommendations: javascript video tutorial, web front-end】
JavaScript object-oriented - properties Descriptor
JavaScript actually supports a variety of programming paradigms, including functional programming and object-oriented programming:
- Objects in JavaScript are designed as an unordered set of attributes Collection , like a hip-hop table, consists of key and value;
- key is an identifier name, and value can be any type, or other object or function type;
- If the value is a function, then we can call it The method of the object;
1. How to create an object?
- The most common way to create objects in the early days is to use the Object class, and use the new keyword to create an object, and then store the properties or methods into the object:
var obj = new Object() obj.name = 'why' console.log(obj.name, obj) // why { name: 'why' }
- Later, for the sake of convenience, many developers created objects directly in the form of literals:
// 字面量方式 var obj2 = { name: 'jam', age: '8' } console.log(obj) // { name: 'jam', age: '8' }
2. Manipulate the properties of the object - property descriptor
Before, our properties were directly defined inside the object, or added directly to the object;
But in this way we cannot impose some restrictions on this property: for example, whether this property can be passed delect
Can deletion be traversed during for-in
traversal?
If we want to control an attribute more accurately, then I can use Attribute descriptor. The properties of an object can be accurately added or modified through property descriptors;
Property descriptors require the use of Object.defineProperty
to add or modify properties.
Attribute descriptors are divided into two types: data descriptors and access descriptors
2.1 Data descriptors
A data descriptor is a property with a value that may or may not be writable. The data descriptor has the following optional key values:
- value: The value corresponding to this attribute. Can be any valid JavaScript value (numeric value, object, function, etc.). The default is undefined.
- writable: If and only if the writable of this attribute is true, the value can be changed by the copy operator. The default is false.
- configurable: If and only if the attribute's configurable is true, the attribute descriptor can be changed, and the attribute can also be deleted from the corresponding object. The default is false.
- enumerable: If and only if the enumerable of the property is true, the property can appear in the enumeration property of the object. The default is false.
2.2.1. Get the property descriptor Object.getOwnPropertyDescriptor()
The Object.getOwnPropertyDescriptor() method returns the property corresponding to the own property on the specified object. Property descriptor.
Object.getOwnPropertyDescriptor(obj,prop)
- obj: The target object to be found
- prop: The name of the property in the target object (String type).
- Return value: If the specified property exists on the object, return its property descriptor object, otherwise return undefined.
Note: If the first parameter of this method is not an object, an error (TypeError) will be reported.
2.1.2. Set the property descriptor Object.defineProperty
The Object.defineProperty() method will directly define a new property on an object, or Modifies an existing property of an object and returns the object.
Object.defineProperty(obj,prop,descriptor)
- obj: The object on which the properties are to be defined.
- prop: The name of the property to be defined or modified.
- descriptor: the property descriptor that will be defined or modified
- Return value: the object passed to the function
如下示例代码展示了属性描述符的设置和获取 var obj = { name: 'jam', age: 8 } Object.defineProperty(obj, 'job', { value: '律师' }) console.log(Object.getOwnPropertyDescriptor(obj, 'age')) // { value: 8, writable: true, enumerable: true, configurable: true } console.log(obj.job) // 律师 // 通过defineProperty新增的属性,该新属性是不可修改、不可删除以及不可枚举的 console.log(Object.getOwnPropertyDescriptor(obj, 'job')) // {value: '律师',writable: false,enumerable: false,configurable: false}
Note: Properties added through defineProperty are non-modifiable, non-deletable and non-enumerable
(1) Whether configurable can be deleted on the object
var obj = { name: 'jam', age: 8 } Object.defineProperty(obj, 'address', { value: '河北', // configurable 该属性不可删除,更不可再次使用defineProperty修改属性描述符 configurable: false, }) delete obj.address // 想使用delete删除该属性 obj.address = '广州' // 想修改obj中的属性address值为广州 console.log(obj.address) // 输出结果:河北
Because the attribute descriptor configurable value is false and cannot be deleted or modified, neither delete nor modification takes effect
(2) Whether enumerable can be enumerated and traversed
var obj = { name: 'jam', age: 8}Object.defineProperty(obj, 'sex ', { value: '男', // enumerable 配置该属性是否可以枚举 enumerable: true})for (i in obj) { console.log(i)}
When enumerable: false, the output result is name age
When enumerable: true, the output result is name age sex
(3) writable This feature controls whether the attribute can be assigned a value (write a value)
var obj = { name: 'jam', age: 8}Object.defineProperty(obj, 'score', { value: 80, // writable: true writable: false})obj.score = 100 console.log(obj.score) // 80
Because the value of writeable is false, when the score is modified to 100, the modification is not successful. The final output is 80
2.1.3、同时设置多个属性描述符 Object.defineProperties
是不是感觉每次只能设置一个属性的属性描述符很繁琐,Object.defineProperties可以帮你解决问题。
Object.defineProperties()方法为对象定义一个或多个新属性或修改现有属性,并返回该对象。
Object.defineProperties(obj,props)
- obj:要在其上定义属性的对象。
- props:要定义其可枚举属性或修改的属性描述符的对象。
- 返回值:被传递给函数的对象。
示例代码如下:
var obj = { name: 'jam',}Object.defineProperties(obj, { 'age': { value: 28, writable: true, configurable: false, enumerable: true }, 'job': { value: '律师', writable: true, configurable: false, enumerable: true }, 'sex': { value: '男', writable: false, configurable: false, enumerable: true }, 'height': { value: '1.8 m', writable: false, configurable: false, enumerable: true }})console.log(obj) // name: 'jam', age: 28, job: '律师', sex: '男', height: '1.8m' }
2.2存取描述符
存取描述符是由getter-setter函数对描述的属性。存取描述符具有以下可选键值:
- get:给属性提供getter的方法,如果没有getter则为undefined。当访问该属性时,该方法会被执行,方法执行时没有参数传入,但是会传入this对象。
- set:给属性提供setter的方法,如果没有setter则为undefined。当属性值修改时,触发执行该方法。该方法将接受唯一参数,即该属性新的参数值。
- configurable:当且仅当该属性的configurable为true时,该属性描述符才能够被改变,同时该属性也能从对应的对象上被删除。默认为false。
- enurnerable:当且仅当该属性的enurnerable为true时,该属性才能够出现在对象的枚举属性中。默认为false。
configurable 和 enurnerable 的使用与数据描述符中的一致,这里就不过多讲解了。
主要讲一下get 和 set 方法的使用
2.2.1 get()与set()的使用
var obj = { name: 'jam', age: 8, _address: '河北' } // 存取描述符的使用场景 // 1.隐藏某一个私有属性被希望直接被外界使用和赋值 // 2.如果我们希望解惑某一个属性它访问和设置值的过程时,也会使用存储属性描述符 Object.defineProperty(obj, 'address', { enumerable: true, configurable: true, get: function () { foo() return this._address }, set: function (value) { bar() this._address = value } }) function foo () { console.log("截获了一次address的值") } function bar () { console.log("设置了一次address的值") }
上述示例代码控制台打印结果如下:
【相关推荐:javascript视频教程、web前端】
The above is the detailed content of JavaScript object-oriented detailed analysis of property descriptors. 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



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

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

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP 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

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
