본문으로 바로가기

call/apply 와 생성자

call / apply 가 생성자에 사용되면 다른 생성자에 정의된 인스턴스 멤버를 가져와서 정의할 수 있습니다.




다음과 같은 Person, Korean 생성자가 있다고 가정합니다.

JavaScript
function Person(name) {
    this.name = name;
}

function Korean(city) {
    this.city = city;
}



Korean 에서 Person 에 정의되어 있는 인스턴스 멤버를 가져오고 싶은 경우에 call/apply 를 사용할 수 있다는 것입니다.

JavaScript
function Korean(city) {
    // 생성자 Person 에 대해 call/apply 를 호출한다.
    Person.call(this, name) // Person.apply(this, [name])
    this.city = city;

}

Korean 생성자 내부에서 Person.call(this, name) 을 호출하면 이 때의 this 는 현재 생성된 Korean 인스턴스가 됩니다.

결국 Person 생성자 내부에서 this 를 통해 멤버를 정의하면 결구 그 멤버는 Korean 인스턴스의 멤버가 되는 것입니다.



Jaehee's WebClub


'JavaScript > this 키워드' 카테고리의 다른 글

call/apply & this 값 설정  (2) 2016.10.04
this 총정리  (0) 2016.10.04
bind()와 this  (0) 2016.10.04
apply()와 this  (0) 2016.10.04
call()과 this  (0) 2016.10.04