search
HomeWeb Front-endJS TutorialSummary 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><p><strong>2. Property name expression</strong></p>
<p>There are two ways to define the properties of an object in JavaScript. </p>
<pre class="brush:php;toolbar:false">//方法一
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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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 the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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 vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function