Introduction to new ECMAscript object features

Introduction to new ECMAscript object features

1. Object properties

1.1 Attribute Notation

ECMAScript 2015 allows variables and functions to be written directly inside curly braces as properties and methods of objects. This way of writing is more concise.

The sample code is as follows:

let name = 'A bowl of Zhou'
let job = 'Front-end engineer'

// Attribute notation is written directly to the variable let obj1 = {
  name,
  job,
  sayMe() {
    console.log(name)
  }
}
// Equivalent to let obj2 = {
  name: name,
  job: job,
  sayMe: function() {
    console.log(name)
  }
}
console.log(obj1, obj2);

2. Calculate the property name

In JavaScript , we define properties in two ways: brackets [] or.:

// Method 1 obj.foo = true;
// Method 2 obj['a'+'bc'] = 123;


The . operator has significant limitations. For example, attributes such as first name can only be defined using square brackets. The bracket approach allows us to define properties using variables or string literals that would result in a syntax error when using identifiers.

For example:

let person = {},
  lastName = "last name";

person["first name"] = "Nicholas";
person[lastName] = "Zakas";
console.log(person["first name"]); // "Nicholas"
console.log(person[lastName]); // "Zakas"

These two methods can only be defined using square brackets. In ES5, you can use string literals as properties in object literals, for example:

let person = {
  "first name": "Nicholas"
};
console.log(person["first name"]); // "Nicholas"


However, when our attribute name exists in a variable or needs to be calculated, it is impossible to define the attribute using object literals.

Before ES5, if the property name is a variable or needs to be dynamically calculated, it can only be accessed through object.[variable name].

let p = {
  name : 'Li Si',
  age: 20
}
let attName = 'name';
console.log(p[attName]) //Here attName represents a variable name.
// Li Si

Moreover, this method of dynamically calculating attribute names cannot be used in literals.

let attName = 'name';
  let p = {
    attName : '李四', // Here attName is the attribute name, which is equivalent to defining an attribute with the attribute name attName at each level of p.
    age: 20
  }
console.log(p[attName]) // undefined


In ECMAScript 2015 , you can enclose the property name in [ ] to reference pre-defined variables in the brackets.

let attName = 'name';
  let p = {
    [attName]: 'Li Si', // references the variable attName. This is equivalent to adding an attribute named name with age: 20
  }
console.log(p[attName]) // Li Si

The brackets in an object literal indicate that the property name is to be evaluated, and its contents are evaluated as a string.

3.Object methods

3.1Object.is() method

ECMAScript 2015 has only two operators for comparing two values ​​for equality: the equality operator ( == ) and the strict equality operator ( === ).

  • However, both operators have disadvantages
  • When using the equality operator, data types are automatically converted

The strict equality operator causes NaN to be unequal to itself, and +0 to be equal to -0.

ECMAScript 2015 proposed the " Same-value equality algorithm to solve this problem. Object.is is a new way to deploy this algorithm. It is used to compare whether two values ​​are strictly equal, and the behavior is basically the same as the strict comparison operator (===).

The syntax structure is as follows:

Object.is(value1, value2);


Parameter Description:

  • value1 : The first value to be compared.
  • value2 : The second value to be compared.

Returns a Boolean value.

The sample code is as follows:

console.log(+0 === -0); //true
console.log(NaN === NaN); // false

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

3.2Object.assign() method

Object.assign() method is used to assign the values ​​of all enumerable properties from one or more source objects to a target object. It will return the target object.

The syntax structure is as follows:

Object.assign(target, ...sources)


Parameter Description:

  • target : target object
  • sources : source object

It is worth noting that if a property in the target object has the same key, the property will be overwritten by the property in the source object. The properties of the later source objects will similarly override the properties of the earlier source objects.

The sample code is as follows:

let sources = {
  name: 'A bowl of Zhou',
  job: 'Front-end engineer'
}
let target = {}
// Use the assign() method to assign the values ​​of all enumerable properties from one or more source objects to the target object.
Object.assign(target, sources)
console.log(target);
// Verify whether it is a deep copy target.name = 'a bowl of porridge'
console.log(target, sources); //{ name: '一碗周', job: 'Front-end siege lion' } { name: '一碗粥', job: 'Front-end siege lion' }


4.super keyword

We know that the this keyword always refers to the current object where the function is located. ECMAScript 2015 adds another similar keyword, super, which points to the prototype object of the current object.

// Define an object to be used as a prototype object const proto = {
  v: 'Hello'
}
// Define an object const obj = {
  v: 'World',
  printV1() {
    console.log(this.v);
  },
  // Using the super keyword printV2() {
    console.log(super.v);
  }
}
//Change the prototype of the obj object to prtot
Object.setPrototypeOf(obj, proto)
// Usage of this obj.printV1() // World
// Usage of super obj.printV2() // Hello


It is worth noting that when the super keyword represents a prototype object, it can only be used in the object's method. Using it anywhere else will result in an error. Currently, only the object method shorthand can allow JavaScript engine to confirm that the method defined is an object method.

5. Object extension operator

The object spread operator ( ... ) is used to extract all traversable properties of the parameter object and copy them to the current object.

The sample code is as follows:

// The object extension operator (...) is used to extract all traversable properties of the parameter object and copy them to the current object.
let obj = {
  name: 'A bowl of Zhou',
  job: 'Front-end engineer'
}
let newObj = {
  ...obj
}
console.log(newObj); // { name: 'Yiwan Zhou', job: 'Front-end engineer' }
// Verify whether it is a deep copy newObj.name = 'A bowl of porridge'
console.log(obj, newObj); // { name: '一碗周', job: 'Front-end siege lion' } { name: '一碗粥', job: 'Front-end siege lion' }


Since arrays are special objects, the object spread operator can also be used for arrays.

let arr = [1, 2, 3, 4, 5]
let obj = {
  ...arr
}
console.log(obj); // { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }


If the spread operator is not followed by an object, it will be automatically converted to an object.

console.log(
  {
  ...1 // equivalent to {...Object(1)}
  }
); // {}
console.log(
  {
  ...true // equivalent to {...Object(true)}
  }
); // {}
console.log(
  {
  ...undefined // equivalent to {...Object(undefined)}
  }
); // {}
console.log(
  {
  ...null // equivalent to {...Object(null)}
  }
); // {}

This is the end of this article about the introduction of new feature objects of ECMAscript. For more relevant ECMAscript object introduction content, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript Learning Summary (I) ECMAScript, BOM, DOM (Core, Browser Object Model and Document Object Model)
  • Detailed explanation of ECMAScript6 introduction--Class object
  • In-depth understanding of JavaScript series (18): ECMAScript implementation of object-oriented programming
  • Object accessor properties in ECMAScript5: introduction to getters and setters

<<:  Use thead, tfoot, and tbody to create a table

>>:  Solve the problem of 8 hours difference between docker container and host machine

Recommend

Detailed explanation of Angular routing sub-routes

Table of contents 1. Sub-route syntax 2. Examples...

Win2008 Server Security Check Steps Guide (Daily Maintenance Instructions)

The document has been written for a while, but I ...

10 Tips for Mobile App User Interface Design

Tip 1: Stay focused The best mobile apps focus on...

How to install Elasticsearch7.6 cluster in docker and set password

Table of contents Some basic configuration About ...

HTML Several Special Dividing Line Effects

1. Basic lines 2. Special effects (the effects ar...

Detailed examples of Docker-compose networks

Today I experimented with the network settings un...

Node.js solves the problem of Chinese garbled characters in client request data

Node.js solves the problem of Chinese garbled cha...

Docker installation of MySQL (8 and 5.7)

This article will introduce how to use Docker to ...

MySQL 8.0.12 installation and configuration graphic tutorial

Recorded the download and installation tutorial o...

How to choose the right index in MySQL

Let’s take a look at a chestnut first EXPLAIN sel...

How to use Linux paste command

01. Command Overview The paste command will merge...