Deep understanding of ES6--4. Extended object functionality

The main knowledge points are object category, property shorthand, method shorthand, property name to be calculated, Object.is() method, Object.assign() method, properties that can be repeated, the enumeration order of own properties, Object.setPrototypeOf () method, super reference, method definition

Extended Object Function Knowledge Points

1. Object class

Objects come in the following categories:

  • Ordinary objects: have all the default internal behavior of JS objects;
  • Exotic objects: their internal behavior differs from the default behavior in some respects;
  • Standard objects: objects defined in ES6, such as Array, Date, etc.;
  • Built-in objects: objects provided by the JS runtime environment when the script starts running, all standard objects are built-in objects

2. Extensions to Object Literal Syntax

Shorthand for property initialization

The property initializer shorthand can be used to eliminate duplication of property names and local variables by assigning the same-named property with the value of a variable in scope:

function createPerson(name,age){
    return {
        name:name,
        age:age
    }
}

//由于属性名和本地变量名相同,可以采用
//属性初始化器的速记法,等价于


function createPerson(name,age){
    return {
        name,
        age
    }
}

method shorthand

In the writing method of object literal, adding a method to an object requires specifying the properties of the object and the specific function declaration. ES6 provides a method shorthand syntax. By omitting the function keyword, the syntax for adding methods to objects can be more concise. There is one important difference: method shorthands can be used super, but non-shorthand methods cannotsuper .

//方法简写法

let person = {
    sayName:function(){
        return name;
    }

}

//等价于
let person = {
    sayName(){
        return name;
    }

} 

Computed property name

Computed property names rule allows property names in object literals to be variables, string literals, or computed from variables, by including property names in square brackets [].

//需计算属性名
let person = {};
let firstName = 'first name';
let suffix = '@github.com'
let email = 'email';
//变量
person[firstName] = 'hello';
//字符串字面量
person['last name']= 'world';
//变量计算而得到的
person[email+suffix] = '[email protected]'

Object.is()

In JS ,=== the strict equality operator is used when comparing whether two values NaN===NaN) method to judge these two situations will be different from using the strict equality operator, and other situations are basically the same as using the strict equality operator;

console.log(+0==-0);  //true
console.log(+0===-0); //true
console.log(Object.is(+0,-0)); //false

console.log(NaN==NaN); //false
console.log(NaN===NaN); //false
console.log(Object.is(NaN,NaN)); //true

console.log(5=='5'); //true
console.log(5==='5'); //false
console.log(Object.is(5,'5')) //false

Object.assign()

An object obtains properties and methods from another object. This is a typical mixin pattern. The Object.assign() method can implement object mixins more concisely. This method requires a receiver object and several provider objects. Receivers will receive their properties in the order in which the providers are listed in the parameters, which means that the second provider may overwrite the same properties of the first provider;

let person={
    name:'hello',
    age:18
}
let car ={
    brand:'BWM',
    age:5
}
let obj = {};
Object.assign(obj,person,car);
console.log(obj); //{name: "hello", age: 5, brand: "BWM"}

The Object.assign() method does not create accessor properties on the receiver, even if the provider has accessor properties, because the Object.assign() method uses the assignment operator, the provider's accessor properties are converted to the receiver's data Attributes;

let receiver = {},
supplier = {
    get name() {
        return "file.js"
    }
};
Object.assign(receiver, supplier);
let descriptor = Object.getOwnPropertyDescriptor(receiver, "name");
console.log(descriptor.value); // "file.js"
console.log(descriptor.get); // undefined

Duplicate properties allowed

In ES5 strict mode, properties in object literals are checked for duplicates, and an error is thrown if they are duplicated. In ES6, whether in strict mode or non-strict mode, the attribute is no longer checked for repetition. When the attribute is repeated, the latter attribute will overwrite the former attribute;

//重复的属性

    let person = {
        name:'hello',
        name:'world'
    }

    console.log(person.name); //world

Enumeration order of own properties

ES6 specifies the enumeration order of its own properties, which will follow the enumeration order of numeric type keys -> string type keys -> symbol type keys:

  1. All numeric type keys, in ascending order;
  2. all string type keys, in the order in which they were added to the object;
  3. All symbol types, also in order of addition

    //The enumeration order of own properties

    var obj = {
    a: 1,
    0: 1,
    c: 1,
    2: 1,
    b: 1,
    1: 1
    };
    obj.d = 1;
    console.log(Object.getOwnPropertyNames(obj).join(“”));//012acbd

3. More Powerful Prototypes

Modify object prototype

In ES6, the prototype of the object can be modified through the Object.setPrototypeOF() method, which contains two parameters: one is the object whose prototype is to be modified, and the other is the prototype to be specified;

let person = {
    getName(){
        return 'hello';
    }
}
let dog ={
    getName(){
        return 'world';
    }
}

let friend = Object.create(person); 
console.log(friend.getName()); //hello
console.log(Object.getPrototypeOf(friend)===person); //true

Object.setPrototypeOf(friend,dog); 
console.log(friend.getName()); //world
console.log(Object.getPrototypeOf(friend)===dog); //true

use super reference

You can use superreferences to access methods in the prototype. If you need to override the method of the same name in the object, you can do this:

let person = {
    getName(){
        return 'hello';
    }
}
let dog ={
    getName(){
        return super.getName()+' world';
    }
}



Object.setPrototypeOf(dog,person);
console.log(dog.getName()); //hello world

If super reference is used, it can only be used in method shorthand, otherwise an error will be reported:

let dog ={
    getNanem:function (){
        return super.getName()+' world';
    }
}
报错:Uncaught SyntaxError: 'super' keyword unexpected here

method definition

Before ES6, the concept of a method was never formally defined, but in ES6: a method is a function with a [[HomeObject]] internal property that points to the object to which the method belongs;

//方法
let person = {
    getName(){
        return 'hello';
    }
}
//不是方法
function getName(){
    return 'hello world';
}

4. Summary

ES6 makes ES6 easier to use and more powerful by extending the object function. There are some specific improvements in the object function:

For object literals:

  1. Shorthand properties make it easier to assign the value of a variable in scope to a property of the same name;
  2. The rules for calculating attribute names can more conveniently use variables, string literals, and the results of variable calculations as attributes;
  3. The method shorthand can omit the function keyword and the colon: to make the definition of the method more concise;
  4. The check for duplicate attributes is discarded, and the latter attributes overwrite the attribute values ​​of the former attributes with the same name;
  5. Specifies the enumeration order of the object's own properties for numeric type keys -> string type keys -> symbolic type keys.

For the object prototype:
1. The Object.assign() method can integrate the properties of multiple provider objects into the receiver object, which can facilitate the realization of the object's mixing mode;
2. The Object.is() method is more efficient in handling special values ​​than The strict comparator is safer;
3. The Object.setPrototypeOf() method can more easily change the prototype of an object;
4. Provide the super keyword to access methods on the prototype.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324692840&siteId=291194637