Home  >  Article  >  Web Front-end  >  Summary of the extensions and new methods of ES6 objects (with examples)

Summary of the extensions and new methods of ES6 objects (with examples)

不言
不言forward
2019-01-11 11:02:233425browse

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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete