


Summary of the extensions and new methods of ES6 objects (with examples)
This article brings you a summary of the expansion and new methods of ES6 objects (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .
1. Concise representation of attributes
ES6 allows variables and functions to be written directly as properties and methods of objects. This kind of writing is more concise.
const foo = 'bar'; const baz = {foo}; baz//{foo:'bar'} //等同于 const baz = {foo:foo}
The above code shows that ES6 allows variables to be written directly in objects. At this time, the attribute name is the variable name, and the attribute value is the value of the variable. Here's another example.
function f(x,y){ return {x,y} } //等同于 function f(x,y){ return {x:x,y:y}; } f(1,2)//{x:1,y:2}
In addition to attribute abbreviations, methods can also be abbreviated.
const o ={ method(){ return 'Hello!' } } //等同于 const o = { method:function(){ return 'Hellow'; } }
The following is a practical example.
let birth = '2000/01/01'; const Person ={ name:'张三', //等同于birth:birth birth, //等同于hello :function().... hello(){ console.log('我的名字是',this.name) } }
This way of writing will be very convenient for the return value of a function.
function getPoint(){ const x =1; const y = 10; return {x,y} } getPoint()//{x:1,y:10}
The CommonJS module outputs a set of variables, which is very suitable for concise writing.
let ms = {}; function getItem(key){ return key in ms ?ms[key]:null; } function setItem(key,value){ ms[key] = value; } function clear(){ ms={} } module.exports = {getItem,setItem,clear}; //等同于 module.exports = { getItem:getItem, setItem:setItem, clearLclear }
The attribute assigner (setter) and value getter (getter) are actually written in this way.
const cart = { _wheels:4, get wheels(){ return this._wheels; }, set wheels (value){ if(value<this._wheels){ throw new Error('数值太小了!'); } this._whells = value; } }
2. Property name expression
There are two ways to define the properties of an object in JavaScript.
//方法一 obj.foo = true; //方法二 obj['a'+'bc'] = 123;
The first method of the above code is to directly use the identifier as the attribute name, and the second method is to use the expression as the attribute name. In this case, put the expression within square brackets.
However, if you use literals to define objects (using curly brackets), you can only use method one (identifier) to define properties in ES5.
var obj ={ foo:true, abc:123 }
When ES6 allows literal definition of an object, use method 2 as the property name of the object, that is, put the expression in parentheses.
let propKey = 'foo'; let obj ={ [propKey]:true, ['a'+'bc']:123 }
Here is another example:
let lastWord = 'last word'; const a = { 'first word':'hello', [lastWord]:'world' }; a['first word']//hello a[lastWord]//world a['last word']//world
Expressions can also be used to define method names.
let obj = { ['h'+'ello'](){ return 'hi' } } obj.hello()//hi;
Note:
属性名表达式与简洁表示法,不能同时使用,会报错。 属性名表达式如果是一个对象,默认情况下会自动将对象转为字符串[object object],这一点要特别小心。
const keyA = {a:1}; const keyB = {b:2}; const myObject = { [keyA]:'valueA', [keyB]:'valueB' }; myObject;// Object {[object Object]: "valueB"}
In the above code, [keyA] and [keyB] get [object object], so [keyB] will overwrite [keyA], and myObject There is only one [object object] attribute at the end.
The name attribute of the method
The name attribute of the function returns the function name. Object methods are also functions, so they also have a name attribute.
const person = { sayName() { console.log('hello!'); }, }; person.sayName.name // "sayName"
Enumerable type and traversal of attributes
Each attribute of the object has a description object, which is used to control the behavior of changing the attribute. The Object.getOwnPropertyDescriptor(obj,'foo') method can obtain the description object of the property.
Describes the enumerable attribute of an object, which is called enumerability. If this attribute is false, it means that some operations will ignore the current attribute.
Currently, there are four operations that ignore attributes whose enumerable is false.
for...in循环:只遍历对象自身的和继承的可枚举的属性。(不包含Symbol属性) Object.keys():返回对象自身的所有可枚举的属性的键名,返回一个数组。(不包含Symbol) JSON.stringify():只串行化对象自身的可枚举的属性。 object.assign():忽略enumrable为false的属性,只拷贝对象自身的可枚举的属性。
ES6 has a total of 5 methods to traverse the properties of an object.
(1)for...in
for...in循环遍历对象自身的和继承的可枚举属性(不包含Symbol属性)。
(2)Object.keys(obj)
object.keys返回一个数组,包含对象自身的(不含继承的)所有可枚举属性(不包含Symbol属性)的键名。
(3)Object.getOwnPropertyNames(obj)
返回一个数组,包含对象自身的所有属性(不含Symbol属性,但是包括不可枚举属性)的键名。
(4) Object.getOwnPropertySymbols(obj)
返回一个数组,包含对象自身的所有Symbol属性的键名。
(5) Reflect.ownKeys(obj)
Reflect.ownKeys返回一个数组,包含对象自身的所有键名,不管键名是Symbol或字符串,也不管是否可枚举。
super keyword
We know that this keyword always points to For the current object where the function is located, ES6 has added another similar keyword super, which points to the prototype object of the current object.
const proto = { foo:'hello' }; const obj = { foo:'world', find(){ return super.foo; } }; Object.setPrototypeOf(obj,proto); obj.find();//hello
In the above code, in the object obj.find() method, the foo attribute of the prototype object proto is referenced through super.foo.
Note: When the super keyword represents a prototype object, it can only be used in the object's method. If used elsewhere, an error will be reported. Currently, only the object method abbreviation allows the Javascript engine to confirm that the object method is defined.
Inside the JavaScript engine, super.foo is equivalent to Object.getPrototypeOf(this).foo or Object.getPrototypeOf(this).foo.call(this).
Extension operator of object
Destructuring assignment
The destructuring assignment of object is used to get the value from an object, which is equivalent to all the traversable but not yet read parts of the target object itself. Attributes are assigned to the specified object. All keys and their values will be copied to the new object.
let{x,y,...z} = {x:1,y:2,a:3,b;4}; x//1, y//2, z//{a:3,b:4}
In the above code, variable z is the object where the destructuring assignment is located. It takes all the unread keys (a and b) to the right of the equal sign and copies them along with their values.
The above is the detailed content of Summary of the extensions and new methods of ES6 objects (with examples). 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
