상속

상속

객체는 연관된 로직들로 이루어진 작은 프로그램이라고 할 수 있다. 상속은 객체의 로직을 그대로 물려 받는 또 다른 객체를 만들 수 있는 기능을 의미한다.

기존의 로직수정하고 변경해서 파생된 새로운 객체를 만들 수 있게 해준다.

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 />"); //My name is egoing
function Person(name){ // 생성자에 의해 객체가 생성이
    this.name = name;
}
Person.prototype.name=null; // name 이라는 프로포
Person.prototype.introduce = function(){ // introduce 라는 메소드 
    return 'My name is '+this.name; 
}
 
function Programmer(name){
    this.name = name;
}
Programmer.prototype = new Person(); // 객체화 시킴 
 
var p1 = new Programmer('egoing');  // new Programmer -> p1 
document.write(p1.introduce()+"<br />"); //My name is egoing 
// p1 introduce 메소드가 실행
function Person(name){
    this.name = name;
}
Person.prototype.name=null;
Person.prototype.introduce = function(){
    return 'My name is '+this.name; 
}
 
function Programmer(name){
    this.name = name;
}
Programmer.prototype = new Person();
Programmer.prototype.coding = function(){
    return "hello world";
}

function Designer(name){
    this.name = name;
}
 Designer.prototype = new Person();
 Designer.prototype.coding = function(){
    return "beatiful!";
}
 
var p1 = new Programmer('egoing');
document.write(p1.introduce()+"<br />"); //My name is egoing
document.write(p1.coding()+"<br />"); //hello world

var p2 = new Designer('leezche');
document.write(p2.introduce()+"<br />"); //My name is egoing
document.write(p2.coding()+"<br />"); //hello world

Last updated