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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools