preface

In JavaScript, almost every value is an object of some particular type. Es6 also focuses on improving the functionality of objects. Es6 enhances the use of objects in a variety of ways, providing more ways to manipulate and interact with objects through simple extensions of the syntax. Here are some of them.

Object literal syntax extensions

Object literals are just that, we want to create objects, so we don’t have to write redundant code. Directly through its concise syntax. So take a look at what Es6 does for objects.

Shorthand for the initial value of the property

In Es5, object literals are simply keys and collections, which means there is some duplication of initialization properties.

function person(name) {
    return {
        name: name
    }
}
Copy the code

In Es6, the name property is omitted by shorthand for the property, and colons and values are omitted when an object property has the same name as a variable. Look at the following example

function person(name) {
    return {
        name
    }
}
Copy the code

Shorthand syntax for object methods

Es6 also improved the object shorthand method for object literals. In Es5, methods that define objects must have their full names written.

Es5 case

let person = {
    test: function() {}}Copy the code

Es6 case

let person() {
    test(){}}Copy the code

An anonymous expression defined by Es6 object method shorthand, this function has the same properties as Es5. The only difference between Es5 defined object functions and Es6 abbreviated functions is that the abbreviated functions can use super.

Computable attribute name

In Es5, if you want to compute the property name, you need to replace it with [] square brackets.

let person = {}
let value = "hello WaRen"
person["wa ren"] = "Frogman"
person[value] = "value"
Copy the code

In the example above, which is what we do in ES5, if the key value of an object is a variable, we add it using the square brackets of the object.

In Es6, you can use computable property names in object literals. Let’s look at the following example

let key = "name"
let person = {
    [key]: "Frogman" // It is Es6 syntax to use the [] square brackets to define keys in object literals
    [`${key}_test`] :"test"
}
Copy the code

The above use of square brackets in object literals indicates that the property name can be evaluated, that an expression can be written, and that the key value is returned as a string. Remember that using square brackets [] to define key values in object literals is Es6 syntax. I also just know (foundation is not solid -wuwuwu……), the test turn bable conversion Es6 Es5 can see the result.

Duplicate object literal properties

In Es5 strict mode, repeated property validation of object literals is added, and an exception is thrown when multiple properties of the same name exist simultaneously. Here’s an example

"use strict"
var person = {
    name: "Frogman".name: "Zhang" // Syntax errors will be thrown in Es5 strict mode
}
Copy the code

In Es5 strict mode, the second property name triggers a syntax error, but in Es6 the duplicate property check is removed. In Es6, code does not validate duplicate properties in strict mode or not, and for duplicate properties the later overwrite the previous. Ps: This I also just know shed no technical tears…

"use strict"
let person = {
    name: "Frogman".name: "Zhang"
}
Copy the code

In the example above, we can see that this is the Es6 standard. Instead of throwing an exception, the following object overwrites the preceding one, and the last name property is “three”. Our current browser runs on the Es6 standard.

Methods added to the Es6 object

Es6 introduces some new methods on global objects.

Object.is

In Es5, we often use the == equality operator or === congruent operator to compare values. However, in Es5, the equality operator or congruent operator is not completely accurate. For example, +0 and -0 are represented as two different entities in the JavaScript engine. Using the congruent or equality operator returns true, and NaN == NaN returns false. The object. is method takes two arguments and returns true if they are of the same value and type

console.log(+0= = -0) // ture
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(10= ="10") // true
console.log(10= = ="10") // false
console.log(Object.is(10."10")) // false
Copy the code

In the example above, we can see that the object. is method is quite strict, but this is only used for special cases, so we don’t need to throw out == or ===.

Object.assign

The object. assign method can take any number of source objects. The first argument is the receiver, which is the final return value. The second argument is copied into the first argument, so if there are multiple source objects with the same attribute key, the later Object will override the first. Here’s an example

let test1 = {
    name: "Frogman"
}
let test2 = {
    name: "Zhang"
}
let result = Object.assign({}, test1, test2)
console.log(result)  // {name: "name "}
Copy the code

In the example above, you can see that if the above object property has the same name, the following one will override the previous one. If the parameter is passed in as a non-object, it can also be executed, but it will be ignored. Here’s an example

let result = Object.assign({}, 1.2.3)
console.log(result)  / / {}
Copy the code

Note: The object. assign method does not copy the value function (the accessor property) into the Object. Since the object. assign method does the assignment, the Object will eventually be converted to a normal property.

let test = {
    get name() {
      return "Frogman"}}let result = Object.assign({}, test)
console.log(Object.getOwnPropertyDescriptor(result, "name")) // {signals: true enumerable: true value: "writable" : true}
Copy the code

In the example above, you can see the final result of copying the object. The value function is indeed missing, as we can see by obtaining the description property of the object. If you don’t understand the description properties of objects, you can check out my article “Understanding JavaScript Objects in Depth.”

Object.setPrototypeOf

In Es5, we provide the object. getPrototypeOf method to get the prototype of the Object, but Es5 does not provide a method to set the prototype of the Object. If we want to set the prototype of the Object, xx. But it doesn’t make sense. So Es6 provides the object.setPrototypeof method, which takes two arguments. The first is the modified Object and the second is the prototypeobject. Here’s an example

let person = {}
function Fn() {}
let fn = new Fn()
Object.setPrototypeOf(person, fn)
console.log(person)
Copy the code

In the example above, you can see that the person stereotype is changed to the FN stereotype. When you access the Person object, you can see that the fn stereotype has been changed.

Object.values

The object. values method returns an array whose members are of the parameter Object itself, excluding inheritance and stereotypes

let person = {
    name: "Frogman".age: 24.sex: "male"
}
console.log(Object.values(person)) // [" frogman ", 24, "male"]
Copy the code

Object.entries

The object. entries method returns an array (i.e., a two-dimensional array) of key-value pairs for the parameter Object itself, and for properties, excluding inheritance and stereotype entries.

let person = {
    name: "Frogman".age: 24.sex: "male"
}
console.log(Object.entries(person)) // [["name", "frogman "], ["age", 24], ["sex", "male"]]
Copy the code

Object.fromEntries

Object.fromentries is the reverse of object.entries. The return value is an Object used to convert an array of key-value pairs into an Object.

let testArr = [
    ["name"."Frogman"],
    ["age".24],
    ["sex"."male"]]console.log(Object.fromEntries(testArr)) // {name: "frogman ", age: 24, sex: "male"}
Copy the code

Own object property enumeration order

The enumeration order of object attributes is not defined in Es5. It is determined by the JS engine vendor. However, in Es6, the order in which an object’s own properties are returned by an enumeration is specified. The basic rules for owning property enumeration order are as follows:

  • All number keys are sorted in ascending order
  • All string keys are sorted by the order in which they were added to the object
  • All symbol keys are sorted by the order in which they were added
let o = {
    4: 4.1: 1.b: "b".a: "a"
}
o.c = "c"

console.log(Object.keys(o)) // ["1", "4", "b", "a", "c"]
console.log(Object.getOwnPropertyNames(o)) // ["1", "4", "b", "a", "c"]
for (let i in o) {
    console.log(i) // 1 4 b a c
}
Copy the code

In the example above, you can see that the object enumeration properties are returned according to the regular order in Es6. Note that for numeric keys, although the order is arbitrary in object literals, it is regrouped and sorted in enumeration. The string is followed by the numeric key and returned in the order in which the property is placed in the object, followed by the dynamic addition of the string key.

Super reference to simplify prototype access

In Es6, the super keyword is new, which is intended to simplify the use of objects to get the current stereotype. Here’s an example

Es5 case

let person = {
    getName() {
      return Object.getPrototypeOf(this).getVal.call(this)}}let o = {
    getVal() {
      return "Frogman"}}Object.setPrototypeOf(person, o)
console.log(person.getName()) / / frogman
Copy the code

In the example above, you can see that the person stereotype is first set to an o object, and then when the Person object is called, the getName method gets the current stereotype and calls the method on the stereotype, which is the method on the called O object.

Es6 case

let person = {
    getName() {
      return super.getVal.call(this)}}let o = {
    getVal() {
      return "Frogman"}}Object.setPrototypeOf(person, o)
console.log(person.getName()) / / frogman
Copy the code

In the example above, you can see that we have slightly adjusted the above code, replacing object.getPrototypeof with the super keyword. The super keyword is used to access the Object stereotype instead of the object. getPrototypeOf method. But the downside of the super keyword is that it can only be used as a method shorthand for object literals. Let’s look at the following example

let person = {
    getName: function() {
      return super.toString() / / an error}}Copy the code

In example above, a property is defined in the Person object with an anonymous function, and an error is thrown because super references are illegal in the current context. So why is there a difference between the same function and the same function? So let’s move on.

Distinguish the definition of methods correctly

Before Es6, there was no such thing as a method. A method is simply a property that has a function rather than an object. In Es6, a method is formally defined as a function that has an internal [[HomeObject]] property to hold the object to which the method is dependent. Here’s an example

let person = {
    getName() {} / / method
}
function getName() {} // Not a method
Copy the code

In the example above, we define a Person object, which has a getName method. Since we directly assign the function to the person object, the getName method has the value of the [[HomeObject]] property as the Person object. Then look at the getName method defined with the function keyword below. This method is not assigned to an object, so the [[HomeObject]] property is not explicitly defined. If you don’t use the super keyword between these two functions, this little difference isn’t a big deal. But it is especially important to use the super keyword.

Because the super keyword reference determines the subsequent run through the [[HomeObject]] property. The super keyword first finds the current Object (property value) on the [[HomeObject]] property, which is the person, then calls the object.getPrototypeof method to get the current stereotype, then finds the current function of the same name on the destereotype, and finally sets the this binding and calls it. This is why the super keyword error is reported above.

Think write good words that point to praise!

You can also add me to communicate [here]