Home  >  Article  >  Web Front-end  >  A brief introduction to enhanced object literals in ES6

A brief introduction to enhanced object literals in ES6

不言
不言forward
2018-11-14 15:53:272466browse

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.

Overview

In es6, the syntax of object literals has been enhanced

Shorter property declarations

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"}

Shorter function declaration

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 functionKeywords 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}}

Dynamically calculated attribute names

Attribute names can be dynamically changed

let key="name"
let obj={[key]:"jack"} // {name:'jack'}

Overview

let key="name"
let age=23
let person={
    [key]:"jack",
    getName(){return "jack"},
    age
} // {name:"jack",getName:function(){return "jack"},age:23}

Use babel to translate

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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete