ECMAScript 2015 를 시작으로, 객체 초기자(initializer)에 메서드 정의를 위한 더 짧은 구문이 도입되었습니다. 이는 메서드 명에 할당된 함수를 위한 단축입니다.
구문
var obj = {
property( parameters… ) {},
*generator( parameters… ) {},
// 키(속성) 계산값과도 함께:
[property]( parameters… ) {},
*[generator]( parameters… ) {},
// ES5 getter/setter 구문과 비교해 보세요:
get property() {},
set property(value) {}
};
설명
단축 구문은 ECMAScript 5에 도입된 getter 및 setter 구문과 비슷합니다.
다음 코드가 주어지면:
var obj = {
foo: function() {},
bar: function() {}
};
이제 이를 아래로 줄일 수 있습니다:
var obj = {
foo() {},
bar() {}
};
주의 : 단축 구문은 익명(anonymous) 함수 (…foo: function() {}… 에서처럼) 대신 유명(named) 함수를 사용합니다. 유명 함수는 함수 본체에서 호출될 수 있습니다 (이는 참조할 식별자가 없기에 익명 함수에게는 불가능합니다). 자세한 사항은, function 참조.
단축 생성기 메서드
생성기 메서드는 단축 구문을 사용해서도 정의될 수 있습니다. 단축 구문 내 별표(*)는 생성기 속성명 앞에 와야 함을 주의하세요. 즉, * g(){}는 작동하지만 g *(){}는 아닙니다.
// 유명 속성 사용 (ES2015 이전)
var obj2 = {
g: function*() {
var index = 0;
while(true)
yield index++;
}
};
// 단축 구문을 쓰는 같은 객체
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
메서드 정의는 생성 불가능합니다
모든 메서드 정의는 생성자가 아니고 인스턴스화하려고 하는 경우 TypeError 예외가 발생합니다.
var obj = {
method() {},
};
new obj.method; // TypeError: obj.method는 생성자가 아닙니다
var obj = {
* g() {}
};
new obj.g; // TypeError: obj.g는 생성자가 아닙니다 (ES2016에서 바뀜)
예
간단한 테스트 사례
var obj = {
a : "foo",
b(){ return this.a; }
};
console.log(obj.b()); // "foo"
속성 계산명
단축 구문은 속성 계산명(computed property name)도 지원합니다.
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
스펙
| 스펙 | 상태 | 설명 |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Method definitions' in that specification. |
Standard | 초기 정의. |
| ECMAScript 2016 (ECMA-262) The definition of 'Method definitions' in that specification. |
Standard | 생성기 메서드 역시 [[Construct]] 트랩이 없어야 하고 new와 함께 사용되는 경우 예외 발생으로 바뀜. |
| ECMAScript Latest Draft (ECMA-262) The definition of 'Method definitions' in that specification. |
Draft |
브라우저 호환성
We're converting our compatibility data into a machine-readable JSON format.
This compatibility table still uses the old format,
because we haven't yet converted the data it contains.
Find out how you can help!
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Method definition shorthand | 39 | 34 (34) | No support | 26 | No support |
| Generator methods are not constructable (ES2016) | ? | 43 (43) | ? | ? | ? |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Method definition shorthand | No support | No support | 34.0 (34) | No support | No support | No support |
| Generator methods are not constructable (ES2016) | ? | ? | 43.0 (43) | ? | ? | ? |
SpiderMonkey 전용 주의사항
- SpiderMonkey 38 (Firefox 38 / Thunderbird 38 / SeaMonkey 2.35) 이전에, "
get" 및 "set"은 생성기 메서드에 무효한 이름이었습니다. 이는 bug 1073809에서 해결됐습니다. - SpiderMonkey 41 (Firefox 41 / Thunderbird 41 / SeaMonkey 2.38) 이전에, 중괄호는 메서드 정의에 필요하지 않았습니다. ES2015 스펙을 따르기 위해 이제부터 필요하고 이번과 이후 버전에서
SyntaxError가 발생합니다 (bug 1150855).var o = {x() 12}; // SyntaxError - 오직 생성기 메서드만이 생성자인 제한은 SpiderMonkey 41 (Firefox 41 / Thunderbird 41 / SeaMonkey 2.38)에서 구현되었습니다. bug 1059908 및 bug 1166950 참조.