반응형

초창기 자바스크립트 상속 구현 방법

function Person() {
    this.name = 'shiro';
    this.job = 'none';

    this.hello = function() {
        alert('Hello, my name is ' + this.name);
    };
}

function Shiro() {
    var obj = new Person();
    obj.name = 'shiro';
    obj.job = 'Programmer';
    return obj;
}

var shiro = new Shiro();
shiro.hello();

이처럼 초창기 자바스크립트에서 ECMAScript표준의 처리 단계를 우회하여 기본적으로 반환되는 this대신 새로운 obj를 반환하는 방식으로 상속을 구현하였다. 이런 방법은 나름 직관적으로 보이긴 하지만, 치명적 단점이 있다. 바로 shiro변수가 Shiro의 인스턴스가 아닌 Person의 인스턴스로만 인식한다는 점이다.

 

상속 구현 후 객체 유형 인식문제

console.log(shiro instanceof Shiro); // false
console.log(shiro instanceof Person); // true

일반적으로 자바스크립트에서 instanceof를 사용하는 것이 흔한 일은 아니라 불편함을 느끼지는 못할 수도 있지만, 객체지향을 구현하는 정석이 아닌 우회하는 느낌이 강하다. 왜냐하면 new Shiro()로 객체를 생성하였는데, Shiro의 인스턴스로 인식 못하는 것은 객체지향의 관점에서 매우 치명적인 단점이 될 수 있다.

 

따라서 이후 자바스크립트는 function에 기본으로 들어 있는 프로토타입 속성을 새로운 객체로 설정하여 상속하는 방법을 채택하였다. 이 방법은 앞에서 설명한 프로토타입을 새로운 객체로 선언하듯, 상속하고자 하는 객체를 하위 객체의 프로토타입 속성으로 설정하면 된다.

 

객체로 프로토타입을 수정한 자바스크립트 상속 구현

var person = {
    name: 'new',
    hello: function() {
        alert('hello, my name is ' + this.name);
    }
};

function Shiro() {
    this.name = 'Shiro';
}

Shiro.prototype = person;
var shiro = new Shiro();

shiro.hello(); // hello my name is Shiro
person.hello(); // hello my name is new
console.log(shiro instanceof Shiro); // true

코드를 보면 person변수를 객체 표혆식으로 정의하여 객체로 생성하고 있다. 그리고 Shiro()함수로 생성된 shiro객체가 person의 함수를 상속하고 있다.

 

하지만 이때 instanceof Shiro는 정상으로 true가 나오지만, shiro변수가 person변수를 상속했다는 것을 shiro instanceof person과 같은 코드로 확인 할 수 없다. 따라서 프로토타입을 설정할 때 new로 새로운 객체를 만들어서 Shiro.prototype으로 설정하는 방법으로 이러한 문제를 해결하고자 하였다.

 

프로토타입을 이용한 자바스크립트 상속 구현 방법

function Person() {
    this.name = 'new';
    this.hello = function() {
        alert('hello, my name is ' + this.name);
    };
}

function Shiro() {
    this.name = 'Shiro';
}

Shiro.prototype = new Person();

var shiro = new Shiro();

shiro.hello(); // hello, my name is Shiro

console.log(shiro instanceof Shiro); // true
console.log(shiro instanceof Person); // true

이처럼 Person이라는 새로운 생성자를 선언하여 Shiro.prototype에 new Person()으로 객체를 생성하여 선언하면, 일반적인 객체지향을 사용하듯이 shiro instanceof Shiro와 shiro instanceof Person모두 true가 된다. 이는 바로 앞의 상속 방법들과 비교하여 객체지향적인 개발 방법론을 선호하는 개발자들이 만족할만한 결과일 것이다. 

반응형

+ Recent posts