æ¹æ³å®ç¾©
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itâs been available across browsers since 2015å¹´9æ.
èª ECMAScript 2015 éå§ï¼å¼å ¥äºä¸ç¨®æ¼ç©ä»¶åå§å¨ï¼objects initializersï¼ä¸å®ç¾©æ¹æ³çç°¡çèªæ³ãæ¯ä¸åå°å½å¼ææ´¾äºæ¹æ³å稱ç簡便æ¹å¼ã
å試ä¸ä¸
const obj = {
foo() {
return "bar";
},
};
console.log(obj.foo());
// Expected output: "bar"
èªæ³
var obj = {
property( parameters⦠) {},
*generator( parameters⦠) {},
async property( parameters⦠) {},
async* generator( parameters⦠) {},
// with computed keys:
[property]( parameters⦠) {},
*[generator]( parameters⦠) {},
async [property]( parameters⦠) {},
// compare getter/setter syntax:
get property() {},
set property(value) {}
};
說æ
éåç°¡ççèªæ³åå¨ ECMAScript 2015 å¼å ¥ getter 以å setter é¡ä¼¼ã
è«ç以ä¸ç¨å¼ç¢¼ï¼
var obj = {
foo: function () {
/* code */
},
bar: function () {
/* code */
},
};
ä½ å¯ä»¥æå®ç¸®æ¸çºï¼
var obj = {
foo() {
/* code */
},
bar() {
/* code */
},
};
ç¢ç卿¹æ³
ç¢ç卿¹æ³ï¼Generator methodï¼ä¹å¯ä»¥ééç°¡çèªæ³å®ç¾©ä¹ãç¨çæåï¼
- ç°¡çèªæ³çæèï¼*ï¼å¿
é æ¾å¨ç¢ç卿¹æ³ç屬æ§ååé¢ãä¹å°±æ¯èªª
* g(){}è½åä½g *(){}ä¸è¡ï¼ - éç¢ç卿¹æ³çå®ç¾©å¯è½ä¸ææ
yieldééµåãä¹å°±æ¯èªªéå¾çç¢çå¨å½å¼åä¸äºã並æåºSyntaxErrorãAlways useyieldin conjunction with the asterisk (*).
// Using a named property
var obj2 = {
g: function* () {
var index = 0;
while (true) yield index++;
},
};
// The same object using shorthand syntax
var obj2 = {
*g() {
var index = 0;
while (true) yield index++;
},
};
var it = obj2.g();
console.log(it.next().value); // 0
console.log(it.next().value); // 1
Async æ¹æ³
Async æ¹æ³ ä¹å¯ä»¥ééç°¡çèªæ³å®ç¾©ã
// Using a named property
var obj3 = {
f: async function () {
await some_promise;
},
};
// The same object using shorthand syntax
var obj3 = {
async f() {
await some_promise;
},
};
Async generator methods
Generator methods can also be async.
var obj4 = {
f: async function* () {
yield 1;
yield 2;
yield 3;
},
};
// The same object using shorthand syntax
var obj4 = {
async *f() {
yield 1;
yield 2;
yield 3;
},
};
Method definitions are not constructable
All method definitions are not constructors and will throw a TypeError if you try to instantiate them.
var obj = {
method() {},
};
new obj.method(); // TypeError: obj.method is not a constructor
var obj = {
*g() {},
};
new obj.g(); // TypeError: obj.g is not a constructor (changed in ES2016)
ç¯ä¾
>Simple test case
var obj = {
a: "foo",
b() {
return this.a;
},
};
console.log(obj.b()); // "foo"
Computed property names
The shorthand syntax also supports computed property names.
var 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
è¦ç¯
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-method-definitions> |