This article brings you a brief introduction to the enhanced object literals in ES6. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
In es6, the syntax of object literals has been enhanced
If the property's property name and property value are referenced The variable names are consistent and can be omitted directly
let name="jack" // es6之前 var obj={name:name} // {name:"jack"} // es6 let obj={name} // {name:"jack"}
If the attribute name of the attribute is consistent with the function name of the attribute value (function) or the attribute value (function) has no function name, You can omit function
Keywords and attribute names
// es6之前 var obj={sum: function(a, b){return a+b}} // es6 let obj={sum(a, b){return a+b}} //{sum:function(a, b){return a+b}}
Attribute names can be dynamically changed
let key="name" let obj={[key]:"jack"} // {name:'jack'}
let key="name" let age=23 let person={ [key]:"jack", getName(){return "jack"}, age } // {name:"jack",getName:function(){return "jack"},age:23}
Source code
let key="name" let age=23 let person={ [key]:"jack", getName(){return "jack"}, age }
After translation, you can find that it is implemented using Object.defineProperty
"use strict"; var _person; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var key = "name"; var age = 23; var person = (_person = {}, _defineProperty(_person, key, "jack"), _defineProperty(_person, "getName", function getName() { return "jack"; }), _defineProperty(_person, "age", age), _person);
The above is the detailed content of A brief introduction to enhanced object literals in ES6. For more information, please follow other related articles on the PHP Chinese website!