상속

객체 = 변수 + 메소드;

상속은 객체의 로직을 그대로 물려받는 또 다른 객체를 만들 수 있는 기능을 의미한다. 기존의 로직을 수정하고 변경해서 파생된 새로운 객체를 만들 수 있게 해준다.

function person(name) {
    this.name = name;
    this.introduce = function() {
        return 'My name is '+this.name;
    }
}
var p1 = new person('egoing');//객체를 생성하는 생성자.
document.write(p1.introduce()+"<br />");

아래의 코드는 위의 실행결과와 똑같은 결과를 출력한다.

function person(name) {
    this.name = name;
}
person.prototype.name = null;
person.prototype.introduce = function() {
        return 'My name is '+this.name;
}
var p1 = new person('egoing');//introduce 메소드가 실행된다.
document.write(p1.introduce()+"<br />");

상속의 사용 방법

생성자를 prototype에 할당하면 된다.

상속:기능의 추가

Last updated

Was this helpful?