JS adds getter+setter summary
This time I will bring you a summary of adding getter setters in JS. What are the precautions for adding getter setters in JS? The following is a practical case, let’s take a look.
Define getter and setter<br>
1. Specify it when creating the object through the object initializer (it can also be called declaring when creating the object through literal value)
1 2 3 4 5 6 7 8 9 10 11 |
|
The debugging view in chrome is as follows:
You can see that there are more get
attributes and set
attributes
under the object. The output result is as follows:
Of course the get
statement and the set
statement can be declared multiple times to correspond to multiple getters
and setter<br>
The advantage of using this method is that the corresponding getter
and setter<br>
can be declared at the same time when declaring the attribute. Here Someone asked, can the method names of the get and set methods of the o object be changed to "a", so that the method can be accessed directly through "." and operated directly
1 2 3 4 5 6 7 8 9 10 11 |
|
Open chrome to view the creation The view is as follows:
You can see that the get and set methods at this time are different from the above, but do they really work? The answer is no. When we What is called through o.a is the a method declared by the get statement. After entering the method, the this.a method is encountered and the method continues to be called to form an infinite loop, which eventually leads to an infinite loop reporting a memory overflow error.
New syntax (ES6): Currently only supported by firefox, other browsers will report errors
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Open firefox to view debugging:
Output The result is as follows:
2. Use the Object.create method
Quote MDN:
Overview
The Object.create() method creates an object with the specified prototype and several specified properties.Syntax
Object.create(proto, [ propertiesObject ])
We all know that when using the Object.create method to pass a parameter, you can create a prototype based on the parameter. A brief talk about the 8 modes of creating objects in JS
The second parameter is optional and is an anonymous parameter object. The parameter object is a set of attributes and values. The attribute name of the object will be the newly created object. The attribute name, the value is the attribute descriptor (including extended data descriptor or access descriptor, see the following content for specific explanation of what an attribute descriptor is).
Through the property descriptor we can add the get method and set method to the newly created object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
The debugging attempt in chrome is as follows:
You can see that newly created objects have more get and set attributes.
The output results are as follows:
The above example is not used for the get method and set method. Attribute
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
or:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
The output result is as follows:
The advantage of using this method is that it is highly configurable, but Beginners can get confused easily.
3. Use the Object.defineProperty method
Quote MDN:
Summary
The Object.defineProperty() method is directly used in a Define a new property on the object, or modify an existing property, and return the object.
Syntax
Object.defineProperty(obj, prop, descriptor)
Parameters
obj
The object whose properties need to be defined.
prop
The property name that needs to be defined or modified.
descriptor
Descriptor of the attribute that needs to be defined or modified.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
The difference between this method and the previous two is: using the previous two methods, you can only specify getters and setters when declaring the definition. Using this method, you can add or modify them at any time.
If you need to add getters and setters in batches at one time, there is no problem. Use the following method:
4. Use the Object.defineProperties method
MDN:
概述
Object.defineProperties() 方法在一个对象上添加或修改一个或者多个自有属性,并返回该对象。
语法
Object.defineProperties(obj, props)
参数
obj
将要被添加属性或修改属性的对象
props
该对象的一个或多个键值对定义了将要为对象添加或修改的属性的具体配置
不难看出用法与 Object.defineProperty 方法类似
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
输出结果如下:
5.使用 Object.prototype.__defineGetter__ 以及 Object.prototype.__defineSetter__ 方法
1 2 3 4 5 6 7 8 9 10 11 12 |
|
输出结果为1和2
查看 MDN 有如下说明:
什么是属性描述符
MDN:
对象里目前存在的属性描述符有两种主要形式:数据描述符和存取描述符。
数据描述符是一个拥有可写或不可写值的属性。
存取描述符是由一对 getter-setter 函数功能来描述的属性。
描述符必须是两种形式之一;不能同时是两者。
数据描述符和存取描述符均具有以下可选键值:
configurable
当且仅当这个属性描述符值为 true 时,该属性可能会改变,也可能会被从相应的对象删除。默认为 false。
enumerable
true 当且仅当该属性出现在相应的对象枚举属性中。默认为 false。
数据描述符同时具有以下可选键值:
value
与属性相关的值。可以是任何有效的 JavaScript 值(数值,对象,函数等)。默认为 undefined。
writable
true 当且仅当可能用 赋值运算符 改变与属性相关的值。默认为 false。
存取描述符同时具有以下可选键值:
get
一个给属性提供 getter 的方法,如果没有 getter 则为 undefined。方法将返回用作属性的值。默认为 undefined。
set
一个给属性提供 setter 的方法,如果没有 setter 则为 undefined。该方法将收到作为唯一参数的新值分配给属性。默认为 undefined。
以上是摘自MDN的解释,看起来是很晦涩的,具体什么意思呢:
首先我们从以上解释知道该匿名参数对象有个很好听的名字叫属性描述符,属性描述符又分成两大块:数据描述符以及存取描述符(其实只是一个外号,给指定的属性集合起个外号)。
数据描述符包括两个属性 : value 属性以及 writable 属性,第一个属性用来声明当前欲修饰的属性的值,第二个属性用来声明当前对象是否可写即是否可以修改
存取描述符就包括 get 与 set 属性用来声明欲修饰的象属性的 getter 及 setter
属性描述符内部,数据描述符与存取描述符只能存在其中之一,但是不论使用哪个描述符都可以同时设置 configurable 属性以及enumerable
属性。configurable
属性用来声明欲修饰的属性是否能够配置,仅有当其值为 true 时,被修饰的属性才有可能能够被删除,或者重新配置。enumerable
属性用来声明欲修饰属性是否可以被枚举。
知道了什么是属性描述符,我们就可以开始着手创建一些对象并开始配置其属性
创建属性不可配置不可枚举的对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
Enumerable 特性
属性特性 enumerable 决定属性是否能被 for...in 循环或 Object.keys 方法遍历得到
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
输出结果如下:
Configurable 特性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
提高及扩展
1.属性描述符中容易被误导的地方之 writable 与 configurable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
2.通过上面的学习,我们都知道传递属性描述符参数时,是定义一个匿名的对象,里面包含属性描述符内容,若每定义一次便要创建一个匿名对象传入,将会造成内存浪费。故优化如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of JS adds getter+setter summary. 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











Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.
