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