Contents

[JavaScript]Method definitions(js物件裡function縮寫)

ES6 引入了 Method definitions 語法,讓在物件字面值(Object Literal)中定義方法時更為簡潔。

傳統寫法 vs ES6 Method Definitions

ES5 傳統寫法:

1
2
3
4
5
6
7
8
var obj = {
  foo: function() {
    /* code */
  },
  bar: function() {
    /* code */
  }
};

ES6 Method Definitions(縮寫語法):

1
2
3
4
5
6
7
8
var obj = {
  foo() {
    /* code */
  },
  bar() {
    /* code */
  }
};

兩種寫法在功能上幾乎相同,但 ES6 語法更簡潔,是現代 JavaScript 的標準寫法。

與傳統 function 的差異

Method definitions 除了語法更短,還有一個重要差異:不能作為建構函式使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const obj = {
  greet() {
    return 'Hello';
  }
};

// ❌ 錯誤:Method definitions 不能用 new 呼叫
new obj.greet(); // TypeError: obj.greet is not a constructor

// ✅ 傳統 function 可以
const obj2 = {
  greet: function() { return 'Hello'; }
};
new obj2.greet(); // 可以(雖然通常不這樣做)

this 的行為

Method definitions 的 this 與傳統 function 相同,指向呼叫該方法的物件:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const person = {
  name: 'Alice',
  greet() {
    return `Hello, I'm ${this.name}`;
  }
};

person.greet(); // "Hello, I'm Alice"

// 注意:若脫離物件呼叫,this 會遺失
const fn = person.greet;
fn(); // "Hello, I'm undefined"(嚴格模式下會報錯)

其他 ES6 物件相關語法

Shorthand Properties(屬性縮寫)

1
2
3
4
5
6
7
8
const name = 'Alice';
const age = 30;

// ES5
const user = { name: name, age: age };

// ES6 縮寫(變數名稱與屬性名稱相同時可省略)
const user = { name, age };

Computed Property Names(計算屬性名)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const prefix = 'get';

const api = {
  [`${prefix}Name`]() {
    return 'Alice';
  },
  [`${prefix}Age`]() {
    return 30;
  }
};

api.getName(); // "Alice"
api.getAge();  // 30

Generator Methods 與 Async Methods

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const obj = {
  // Generator method
  *generate() {
    yield 1;
    yield 2;
  },

  // Async method
  async fetchData() {
    const data = await fetch('/api/data');
    return data.json();
  }
};

參考資料