JavaScript-物件語法強化

物件語法強化

可以將變數重組為物件

下列程式碼 Lilium 物件內的變數與上面變數有相同的名稱,所以會將相同變數名稱的值帶進物件裡。

const name = "Robert";
const height = 272;

const person = { name, height };
console.log(person); //{ name: 'Robert', height: 272 }

也可以透過物件語法強化來賦予物件方法,因為是 person 呼叫 print 方法,所以此時的 this 是 person 這個物件,person 物件裡的 name 與 height 變數上面已宣告過,所以會將值帶進去 console.log 的結果,就會是

Robert is 272 cm tall

const name = "Robert";
const height = 272;
const print = function () {
  console.log(`${this.name} is ${this.height} cm tall`); //Robert is 272 cm tall
};
const person = { name, height, print };
person.print();

也因新語法(物件語法強化),可在創建物件方法時不需使用 function 關鍵字,可將上列語法簡化成下方程式碼

const name = "Robert";
const height = 272;
const person = {
  name,
  height,
  print() {
    console.log(`${this.name} is ${this.height} cm tall`); //Robert is 272 cm tall
  },
};
person.print();
comments powered by Disqus