ECMAScript 2015 より、オブジェクトイニシャライザのメソッド定義のための短い構文が導入されました。これは、メソッドの名前に割り当てられた関数の省略形です。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
構文
const obj = { get property() {}, set property(value) {}, property( parameters… ) {}, *generator( parameters… ) {}, async property( parameters… ) {}, async* generator( parameters… ) {}, // 算出されたキーも使用可能: get [property]() {}, set [property](value) {}, [property]( parameters… ) {}, *[generator]( parameters… ) {}, async [property]( parameters… ) {}, async* [generator]( parameters… ) {}, };
説明
簡略構文は、ECMAScript 第 5 版で導入された getter や setter 構文に似ています。
次のコードを例にすると:
var obj = {
foo: function() {
/* コード */
},
bar: function() {
/* コード */
}
};
これを以下のように短縮することができます:
var obj = {
foo() {
/* コード */
},
bar() {
/* コード */
}
};
短縮形ジェネレーターメソッド
Generator メソッドは同様に簡略構文を使用して定義することができます。
簡略構文では:
- ジェネレータープロパティ名の前にアスタリスク (*)が 必要です。すなわち、
* g(){}
は動作しますが、g *(){}
は動作しません。 - 非ジェネレーターメソッド定義では
yield
キーワードを入れることはできません。つまり 旧式の ジェネレーター関数 は動作せず、SyntaxError
を投げます。yield
は常にアスタリスク (*
)と一緒に使ってください。
// 名前付きプロパティを使用 (ES6 より前)
const obj2 = {
g: function*() {
let index = 0
while(true)
yield index++
}
};
// 簡略構文を使用して同じオブジェクトを生成
const obj2 = {
* g() {
let index = 0;
while(true)
yield index++
}
};
const it = obj2.g()
console.log(it.next().value) // 0
console.log(it.next().value) // 1
Async メソッド
Async メソッドも簡略構文を使用して定義することができます。
// 名前付きプロパティ
const obj3 = {
f: async function () {
await some_promise
}
};
// 簡略構文を使用して同じオブジェクトを生成
const obj3 = {
async f() {
await some_promise
}
};
Async ジェネレーターメソッド
Generator メソッドも async 関数にすることができます。
const obj4 = {
f: async function* () {
yield 1
yield 2
yield 3
}
};
// 簡略構文を使用して同じオブジェクトを生成
const obj4 = {
async* f() {
yield 1
yield 2
yield 3
}
};
メソッド定義はコンストラクタブルではない
すべてのメソッド定義がコンストラクターではない(簡略構文のみ!)ため、インスタンス化しようとすると TypeError
が発生します。
const obj = {
method() {},
};
new obj.method // TypeError: obj.method is not a constructor
const obj = {
* g() {}
};
new obj.g; // TypeError: obj.g is not a constructor (ES2016 で変更)
例
簡単なテストケース
const obj = {
a: 'foo',
b() { return this.a }
};
console.log(obj.b()) // "foo"
計算されたプロパティ名
簡略構文は計算されたプロパティ名もサポートします。
const bar = {
foo0: function() { return 0 },
foo1(){ return 1 },
['foo' + 2](){ return 2 },
};
console.log(bar.foo0()) // 0
console.log(bar.foo1()) // 1
console.log(bar.foo2()) // 2
// A global function
function foo() {
return 1
}
let name = 'foo'
console.log(window[name]()) // 1
仕様
ブラウザー実装状況
BCD tables only load in the browser
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.