ES6 object literal extension syntax (Enhanced object literals)

Source: Internet
Author: User
object literal extension syntax (Enhanced object literals)

Directory:

Object literal extension syntax Enhanced object literals function Class attribute ellipsis syntax support proto injection dynamically computed property name definition omitted

ellipsis syntax for function class properties

Usage: {method () {...}}

Const OBJ = {
    //before
    foo:function () {
        return ' foo ';
    },

    //after
    Bar () {
        return ' bar ';
    }
}
support proto injection

Developers are allowed to inject __proto__ directly into an object literal, making it an instance of a specified class without having to create another class to implement inheritance.

Import {Eventemitter} from ' Events '

const machine = {
    __proto__: New Eventemitter (),

    method () {/* ... */},
    ...
}

Console.log (machine);  Eventemitter {}
console.log (machine instanceof eventemitter)  //true

machine.on (' event ', msg = Console.log (' Received message: ${msg} '));
Machine.emit (' event ', ' Hello World ');
Received Message:hello World

machine.method (/* ..... *);
property names that can be dynamically computed

The new syntax introduced by ES6 allows us to use an expression directly to express a property name usage: {[statement]: value}

Const prefix = ' ES6 ';
Const OBJ = {
    [prefix + ' enhancedobject ']: ' foo '
}
omit attribute name definition

Sometimes we need to return or pass in some of the values of the variables (or constants) that have already been defined as other object literals, and in most cases these variable names and property names are the same , and we can omit the attribute name definitions.

const foo = 123; Const BAR = () = foo;  Const OBJ = {foo, bar} console.log (obj); {foo:123, bar: [Function]} 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.