티스토리 뷰


Javascript prototype inheritance


자바스크립트에서 상속(inheritance)은 prototype을 이용하여 코드를 재사용할 수 있다.

new 연산자를 이용한 classical한 방식과 Object.create()를 이용한 prototypal한 방식이 있다.


// baseClass
function Person() {
    this.sayJob = false;
}

// prototype method
Person.prototype.say = function () {
    console.log(this.sayJob ? "Yes" : "No");
};

// subClass
function Programmer() {
    Person.call(this);
}

Programmer.prototype = Object.create(Person.prototype);
Programmer.prototype.constructor = Programmer;

var john = new Programmer();
john.say();

// 결과값 : No

Person.call(this)는 baseClass인 person의 property를 subClass인 Programmer에 상속한다.

Object.create() 메서드를 이용하여 Person.prototype을 상속받는다.

마지막으로 Programmer constructor를 Programmer 설정해준다.

this.sayJob = false로 상속받았기 때문에 결과값은 No이다.

// baseClass
function Person() {
    this.sayJob = false;
}

// prototype method
Person.prototype.say = function () {
    console.log(this.sayJob ? "Yes" : "No");
};

// subClass
function Programmer(job, sayJob) {
    Person.call(this);
    this.job = job;
    this.sayJob = sayJob;
}

Programmer.prototype = Object.create(Person.prototype);
Programmer.prototype.constructor = Programmer;

Programmer.prototype.say = function () {
    console.log(this.sayJob ? "I'm a " + this.job : "I'm not a programmer");
};

var john = new Programmer("", false);
var jason = new Programmer("Programmer", true);

john.say();
jason.say();

/* 결과값
I'm not a programmer
I'm a Programmer
*/

위에 코드를 그대로 복사하여 subClass에 property를 추가하고 Programmer.method를 override하였다.

override로 인해 더 이상 Person.prototype.say가 호출되는것이 아니라 Programmer.prototype.say 메서드가 실행된다.


※ 지금까지 알아본 방식은 자바스크립트에서 권장하는 방식인 prototypal 방식이였다.

'Front-end > Javascript' 카테고리의 다른 글

Closure  (0) 2017.02.26
Object creation patterns - factory, constructor, prototype  (0) 2017.02.25
공유하기 링크
댓글
최근에 올라온 글
최근에 달린 댓글
글 보관함
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Total
Today
Yesterday