Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use literals to create objects in ES6

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "how to use literals to create objects in ES6". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Literal syntax extension

Using literals to create objects in ES6 mode is more concise, and for object properties, the initial values of the properties can be abbreviated and computable property names can be used. The definition of object methods eliminates colons and function keywords, as shown in the following example:

/ / Demo1var value = "name", age = 18var person = {age, / / age: age ['my' + value]:' Jenny', / / myname sayName () {/ / sayName: function () console.log (this.myname)}} console.log (person.age) / / 18console.log (person.myname) / / Jennyperson.sayName (); / / Jenny

For the literal attribute of a repeatedly defined object, the ES5 strict mode will check the duplicate property to throw an error, while ES6 removes this mechanism, regardless of strict mode or non-strict mode, the property of the same name will take the last value.

/ / demo2var person = {['my' + value]:' Jenny', myname: 'Tom', myname:' Lee',} console.log (person.myname) / / Lee

New method

One of the design goals followed from ES5 is to avoid creating new global functions or creating new methods on object.prototype.

To make some tasks easier to implement, ES6 introduces some new methods on global Object objects.

Object.is ()

ES6 introduces the Object.is () method to compensate for the inaccurate calculation of congruent operators.

The congruent operator does not trigger a cast type when comparing, and the result of Object.is () is similar, but the comparison results are different for + 0 and-0 (two different entities in the JS engine) and the special value NaN. For example:

/ / demo3console.log (5 = ='5') / / trueconsole.log (5 ='5') / / falseconsole.log (Object.is (5,'5')) / / falseconsole.log (+ 0 = =-0) / / trueconsole.log (+ 0 =-0) / / trueconsole.log (Object.is (+ 0,-0)) / / falseconsole.log (NaN = = NaN) / / falseconsole.log (NaN = NaN) / / falseconsole.log (Object.is (NaN, NaN)) / true

To sum up, Object.is () makes a stricter equivalence judgment on all values. Of course, whether or not to use Object.is () instead of the congruent operator (= =) depends on whether these special cases affect the code.

Object.assign ()

ES6 adds Object.assign () to implement the Mixin mode, where one object receives the properties and methods of another object. Note that you receive rather than inherit, for example, objects in demo1:

/ / demo4var friend = {} Object.assign (friend, person) friend.sayName () / / Jennyconsole.log (friend.age) / / 18console.log (Object.getPrototypeOf (friend) = person) / / false

Before Object.assign (), many JS libraries customized the hybrid method mixin () to implement object composition, with code similar to:

Function mixin (receiver, supplier) {Object.keys (supplier) .forEach (function (key) {receiver [key] = supplier [key]}) return receiver}

You can see that the mixin () method does not copy the accessor property using the "=" assignment operation, and similarly Object.assign () cannot copy the accessor property, but only performs the assignment operation, and the accessor property is eventually transformed into the data property of the receiving object. Examples are as follows:

/ / demo5var animal = {name: 'lili', get type () {return this.name + type}, set type (news) {type = news}} animal.type =' cat'console.log (animal.type) / / lilicatvar pet = {} Object.assign (pet, animal) console.log (animal) / / {name: 'lili', type: [Getter/Setter]} console.log (pet) / / {name:' lili' Type: 'lilicat'}

Object.setPrototypeOf ()

Normally a prototype is specified when it is created through a constructor or Object.create (). ES6 adds the Object.setPrototypeOf () method to change the prototype of the object.

For example, create a coder object that inherits the person object, and then change the prototype of the coder object:

/ / demo6let person = {myname: 'Jenny', sayName () {console.log (this.myname)}} / / create a coder object prototype as person let coder = Object.create (person) coder.sayName () / / Jennyconsole.log (Object.getPrototypeOf (coder) = person) / / truelet hero = {myname:' lee', sayName () {console.log (this.myname)}} / / change the prototype of coder object to heroObject.setPrototypeOf (coder) Hero) coder.sayName () / / leeconsole.log (Object.getPrototypeOf (coder) = hero) / / true

The object prototype is stored in the internal proprietary property [[Prototype]], the value stored in it is returned by calling Object.getPrototypeOf (), and its value is changed by calling Object.setPrototypeOf (). This approach strengthens the manipulation of object prototypes, and the next section focuses on other ways of manipulating prototypes.

Enhanced object prototype

Prototypes are the basis of JS inheritance, and ES6 has made many improvements to prototypes in order to use prototypes in a more flexible way. In addition to the new Object.setPrototypeOf () change prototype, the Super keyword is also introduced to simplify access to the prototype

Super keyword

ES6 introduces Super to make it easier to access object prototypes, and the previous section explained that ES5 can use Object.getPrototypeOf () to return object prototypes. Give an example to illustrate the convenience of Super. When an object needs to reuse a prototype method and redefine its own method, the two implementation methods are as follows:

/ / demo7let coder1 = {getName () {console.log ("coder1 name:") Object.getPrototypeOf (this) .sayName.call (this)} / / set the prototype of the coder1 object to hero (demo6) Object.setPrototypeOf (coder1, hero) coder1.getName () / / coder1 name: leelet coder2 = {getName () {console.log ("coder2 name:") super.sayName ()} Object.setPrototypeOf (coder2, hero) coder2.getName () / / coder2 name: lee

The getName method of the coder1 object also needs call (this) to ensure that it uses the this of the prototype method, which is more complex, and there will be recursive call stack overflow errors in multiple inheritance, and it is simple and safe to use Super directly.

Note that you must use Super in the shorthand method, or an error will be reported, such as the following code running syntax error:

Let coder4= {getName: function () {/ / getName () correct super.sayName () / / SyntaxError: 'super' keyword unexpected here}

Because getName has become an attribute defined by anonymous function in the example, it is illegal to call a Super reference in the current context. If you don't understand, you can take a closer look at the method's dependents.

The dependent object of the method

Before ES6, a "method" was an object property with function rather than data, and ES6 formally defined a method as a function with an internal attribute of [[HomeObject]].

The [[HomeObject]] property stores the dependent objects of the current method, for example:

Let coder5 = {sayName () {console.log ("I have HomeObject")}} function shareName () {console.log ("No HomeObject")}

The value of the [[HomeObject]] property of the sayName () method of the coder5 object is coder5, while the shareName () defined by function does not assign it to the object, so its [[HomeObject]] property is not defined, which is important when using Super.

Super simply calls Object.getPrototypeOf () on the [[HomeObject]] property to get a reference to the prototype, then searches the prototype to get a function with the same name, and finally sets the this binding to call the corresponding method.

Deconstruction assignment

ES6 provides a new feature for array and object literals-deconstruction, which can simplify the process of data extraction and reduce homogenized code. An example of the basic syntax of deconstruction is as follows:

Let user = {name: 'jenny', id: 18} let {name, id} = userconsole.log (name, id) / / jenny 18

Notice that in this code, the user.name is stored in a name variable with the same name as the object property name.

Default value

If the variable name is different from the object property name when deconstructing, that is, it does not exist in the object, then the variable defaults to undefined:

Let user = {name: 'jenny', id: 18} let {name, id, job} = userconsole.log (name, id, job) / / jenny 18 undefined

Non-homonym variable assignment

The default value for a variable with the same name is undefined, but more often it needs to be assigned, and the value of the object property is assigned to the variable with the same name. ES6 provides extended syntax for this, much like the object literal attribute initializer:

Let user = {name: 'jenny', id: 18} let {name, id = 16, job =' engineer'} = userconsole.log (name, id, job) / / jenny 18 engineerlet {name: localName, id: localId} = userconsole.log (localName, localId) / / jenny 18let {name: otherName = 'lee', job: otherJob =' teacher'} = userconsole.log (otherName, otherJob) / / jenny teacher

It can be seen that this syntax is actually opposite to the literal quantity of the object, with the assignment name to the left of the colon and the variable name to the right, and when deconstructing the assignment, it only updates the default value and cannot overwrite the original attribute value of the object.

Nested deconstruction

The syntax for deconstructing nested objects is still similar to the literal amount of objects, and use curly braces to continue to find the underlying structure:

Let user = {name: 'jenny', id: 18, desc: {pos: {lng: 111, lat: 333} let {desc: {pos}} = userconsole.log (pos) / / {lng: 111l, lat: 333} let {desc: {pos: {lng}} = userconsole.log (lng) / / 111let {desc: {pos: {lng: longitude} = userconsole.log (longitude) / /

Object category

The ES6 specification defines the categories of objects, especially for execution environments such as browsers.

Normal (Ordinary) object

Has all the default internal behavior of the JS object

Specific (Exotic) object

Have some internal behaviors that are inconsistent with the default behavior

Standard (Standard) object

Objects defined in the ES6 specification

Can be ordinary objects or specific objects, such as Date, Array, etc.

Built-in object

Objects that exist in the JS execution environment when the script starts execution

All standard objects are built-in objects

That's all for "how to use literals to create objects in ES6". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report