首页 > 代码库 > [ES6] 16. Object Enhancements

[ES6] 16. Object Enhancements

Define object


 

var color = "blue";var speed = 120;var car = {color, speed};console.log(car.color);  // blueconsole.log(car.speed);  // 120

 in ES5: 

var car = {color: color, speed: speed};

 

works with function


var color = "blue";var speed = 120;function go(){    console.log("start");}var car = {color, speed, go};console.log(car.color); //blueconsole.log(car.speed); //120car.go(); // start

 

define function inside object:


 

var color = "blue";var speed = 120;var car = {    color,    speed,    go(){        console.log("start");    }};console.log(car.color); //blueconsole.log(car.speed); //120car.go(); // start

 

in ES5:

var car = {    color,    speed,    go: function(){        console.log("start");    }};

 

get computed property:


 

var color = "blue";var speed = 120;var car = {    color,    speed,    ["go"]: function(){        console.log("start");    }};console.log(car.color); //blueconsole.log(car.speed); //120car.go(); // start

The same as:

car["go"](); // start

 

string concatenation or evaluation


 

var color = "blue";var speed = 120;var drive = "go";var car = {    color,    speed,    [drive]: function(){        console.log("start");    }};console.log(car.color); //blueconsole.log(car.speed); //120car.go(); // startcar["go"](); // start

 

[ES6] 16. Object Enhancements