set
syntax는 어떤 객체의 속성에 이 속성을 설정하려고 할 때 호출되는 함수를 바인드한다.
구문
{set prop(val) { . . . }} {set [expression](val) { . . . }}
매개변수
prop
- 주어진 함수를 바인드할 속성의 이름
val
prop에 설정될 값을 가지고 있는 변수의 별명.
- expression
- ECMAScript 6부터는, 주어진 함수에 바인드 되는 속성 이름은 계산(computed)을 통해 얻을 수 있고 이것을 위한 expressions을 사용할 수 있다.
설명
자바스크립트에서, setter는 특정한 속성에 값이 변경되어 질 때마다 함수를 실행하는데 사용될 수 있다. Setter는 유사(pseudo)-property 타입을 생성하는 getter와 함께 가장 자주 사용된다. 실제 값을 가지는 property와 이 property의 setter 를 동시에 갖는 것은 불가능하다.
set
문법을 사용할 때 다음을 주의한다:
- 숫자혹은 문자로된 식별자를 가질 수 있다;
- 한 개의 파라메터만 가질 수 있다.(더 자세한 정보는 Incompatible ES5 change: literal getter and setter functions must now have exactly zero or one arguments를 본다);
- 오브젝트 리터럴에 동일한 property에 대한 다른 set나 데이터 항목이 올 수 없다.
({ set x(v) { }, set x(v) { } }
그리고{ x: ..., set x(v) { } }
는 허용되지 않는다.)
setter는 delete
operator를 사용하여 제거할 수 있다.
예
새로운 객체의 setter를 객체의 initializer에서 정의하기
다음은 객체 o의 유사 프로러티(pseudo-property )인 current를 정의한다. 이것은 값이 설정될 때, 이 값으로 로그를 갱신 한다.
var o = {
set current (str) {
this.log[this.log.length] = str;
},
log: []
}
다음 사항에 주의한다. current는 정의 되지 않았고 이것에 접근하는 모든 시도는 undefined 값을 얻게될 것이다.
delete operator로 setter를 제거하기
만약 setter를 제거하기 원한다면, 그냥 그것을 delete
하면 된다:
delete o.current;
defineProperty를 사용하여 이미 존재하는 객체에 setter를 정의하기
setter를 이미 존재하는 object에 나중에 언제라도 추가하기 위해서, Object.defineProperty()
를 사용한다.
var o = { a:0 };
Object.defineProperty(o, "b", { set: function (x) { this.a = x / 2; } });
o.b = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
console.log(o.a) // 5
연산된(computed) property name 사용하기
Note: 계산된(Computed) properties는 실험적인 기술이고, ECMAScript 6 proposal의 부분이다. 아직 많은 브라우저가 지원하지 않는다. 이것 때문에 지원하지 않는 환경에서는 문법 오류가 발생할 것이다.
var expr = "foo";
var obj = {
baz: "bar",
set [expr](v) { this.baz = v; }
};
console.log(obj.baz); // "bar"
obj.foo = "baz"; // run the setter
console.log(obj.baz); // "baz"
스펙
Specification | Status | Comment |
---|---|---|
ECMAScript 5.1 (ECMA-262) The definition of 'Object Initializer' in that specification. |
Standard | Initial definition. |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Method definitions' in that specification. |
Standard | Added computed property names. |
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! Desktop Mobile
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 1 | 2.0 (1.8.1) | 9 | 9.5 | 3 |
Computed property names | No support | 34 (34) | No support | No support | No support |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | 1.0 (1.8.1) | (Yes) | (Yes) | (Yes) |
Computed property names | No support | No support | 34.0 (34.0) | No support | No support | No support |
SpiderMonkey-specific notes
- JavaScript 1.8.1부터, object와 array initializers에서 properties를 설정 할 때 setter는 더이상 호출되지 않는다.
- SpiderMonkey 38 부터, rest parameter 를 갖는 setter는 ES6 specification에 따라
SyntaxError
이다.
See also
- getter
delete
Object.defineProperty()
__defineGetter__
__defineSetter__
- Defining Getters and Setters in JavaScript Guide