본문 바로가기

WEB/Javascript

프로퍼티 속성

프로퍼티 이름

value    : 프로퍼티 값    (접근자 프로퍼티 : get)

writable : 프로퍼티 값을 변경할수 있는지 여부 (접근자 프로퍼티 : set)

enumerable : 열거 할수 있는지 없는지. ( for/in 루프에서 읽을 수 있는지 여부)

(ex  - 객체A.x 의enumerable 이 false라면 Object.keys(객체A) x 프로퍼티는 반환 되지 않는다.)

configurable : 프로퍼티 속성값을 변경 여부와 프로퍼티 삭제 가능 여부


* 접근자 프로퍼티란?

일반적인 프로퍼티 이름 : value를 갖는 형식이 아니라

{

x: 1.0,

y: 10.0,

get ratio() {return this.x/this.y},

set ratio(value) { this.x *= value

 this.y  += value * 0.1}

===> 위와 같이 프로퍼티를 정의하고 사용시에는 객체.ratio 사용하면 get ratio() 함수를 호출하게 되고,

객체.ratio = 5 를 하면 set ratio(5) 함수를 호출 한것이 된다.



Object.getOwnPropertyDescriptor(객체, 프로퍼티이름);

- 해당 객체 자신의 (*상속된 프로퍼티 제외) 프로퍼티이름의 속성을 가져온다. 없으면 undefined


Object.defineProperty(객체, 프로퍼티이름, {속성들});

- 프로퍼티 속성 정의 ( * 새로 만들때 속성을 정의 하지 않으면 Default는 undefined 또는 false)

Object.defineProperties(객체, {프로퍼티이름1:{속성1}, 프로퍼티이름2:{속성2}, 프로퍼티이름3:{속성3}});

- 여러 프로퍼티를 한번에 정의


프로퍼티 중 중요한 Prototype (원형)

 prototype은 객체가 생성될때 생성자의 prototype을 객체의 prototype으로 가져간다.

생성자의 모든 프로퍼티를 가져오는 것이 아니다.


[참고]

http://opentutorials.org/module/532/6578


내장 객체에 기능 추가하기

Object.prototype.contain = function(neddle) {
for(var name in this){
if(this[name] === neddle){
return true;
}
}
return false;
}
var o = {'name':'egoing', 'city':'seoul'}
console.log(o.contain('egoing'));

위와 같이 Object.prototype.contain 이란 함수를 만들어주면 모든 생성된 객체에서 contain이란 함수를 사용할수 있다.

(모든 객체는 Object를 상속 받는다)


그러나 이에 따른 문제점이 생긴다. 아래와 같이 o객체의 프로퍼티를 보면 contain이 포함되어 있다.

for(var name in o){
console.log(name);
}


아래와 같이 hasOwnProperty를 이용하면 해당 객체가 직접 소유하고있는 프로퍼티만 출력할 수 있다.

for(var name in o){
if(o.hasOwnProperty(name))
console.log(name);
}



* Object 속성을 확장 하되, 위와 같이 property에 열거 되지 안게 하기 위한 방법

Object.defineProperty(Object.prototype, "contain", { writable : false,         enumerable : false,    // 프로퍼티 열거 여부 contifurable : false, value : function(neddle) { for(var name in this){ if(this[name] === neddle){ return true; } } return false; } });



'WEB > Javascript' 카테고리의 다른 글

클로저  (0) 2014.08.08
bind, apply, call 정리  (0) 2014.08.04
Getter와 Setter 프로퍼티  (0) 2014.07.14