簡寫有兩條基本原則:this
來看下下面這個例子,我分別用ES5 和 ES6 的語法分別定義並聲明瞭一個簡單的學生對象:spa
ES5:code
var studentES5 = { name: '小方哥', age: 20, sex: '男', getName: function () { return this.name; } } console.log('ES5', studentES5); console.log('ES5', studentES5.getName());
ES6:對象
const name = 'Jack'; const age = 25; const sex = '女'; const studentES6 = { name,// 同名的屬性能夠省略不寫 age, sex, getName() {// 能夠省略方法中的 : function return this.name; } }; console.log('ES6', studentES6); console.log('ES6', studentES6.getName());