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

A brief introduction to enhanced object literals in ES6

不言
Release: 2018-11-14 15:53:27
forward
2513 people have browsed it

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"}
Copy after login

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}}
Copy after login

Dynamically calculated attribute names

Attribute names can be dynamically changed

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

Overview

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

Use babel to translate

Source code

let key="name"
let age=23
let person={
    [key]:"jack",
    getName(){return "jack"},
    age
}
Copy after login

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);
Copy after login


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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template