Hi

상속 본문

WEB(웹)/javascript

상속

SharingWorld 2018. 7. 8. 18:02

상속

객체 프로토타입 체인을 이용하여 상속을 구현해낼 수 있다.


클래스 기반 전통적인 상속 방식을 흉내 
클래스 개념 없이 객체의 프로토타입으로 상속을 구현하는 방식(프로토타입을 이용한 상속 -> 객체 리터럴을 중심으로 철저히 프로토타입을 이용하여 상속을 구현해낸다.)

프로토타입을 이용한 상속

부모 객체의 프로퍼티에 접근할 수 있고, 자신만의 프로퍼티를 만들 수도 있다.

function create_object(o) {  
    function F() {}  
    F.prototype = o;  
  return new F();  
}  
  
var person = {  
    name: "zzoon",  
  
  getName: function() {  
        return this.name;  
  },  
  
  setName: function(arg) {  
        this.name = arg;  
  }  
};  
  
var student = create_object(person);  
  
student.setName("me");  
console.log(student.getName()); // (출력값) me

부모 객체에 해당하는 person 객체와 이 객체를 프로토타입 체인으로 참조할 수 있는 자식 객체 student를 만들어서 사용하였다.


extend() 함수로 객체에 자신이 원하는 객체 혹은 함수를 추가시킨다.

var person = {  
    name : "zzoon",  
  
  getName : function() {  
        return this.name;  
  },  
  
  setName : function(arg) {  
        this.name = arg;  
  }  
};  
  
function create_object(o) {  
    function F() {}  
    F.prototype = o;  
  return new F();  
}  
  
function extend(obj, prop) {  
    if (!prop) { prop = obj; obj = this; }  
  
    for (var i in prop) obj[i] = prop[i];  
  
  return obj;  
};  
  
  
var student = create_object(person);  
  
var added = {  
    setAge : function(age) {  
        this.age = age;  
  },  
  getAge : function() {  
        return this.age;  
  }  
};  
  
extend(student, added);  
  
student.setAge(25);  
console.log(student.getAge());

extend() 함수는 사용자에게 유연하게 기능 확장을 할 수 있게 하는 주요 함수고,


상속에서도 자식 크래스를 확장할 때 유용하게 사용됨 

클래스 기반의 상속

function Person(arg) {  
    this.name = arg;  
}  
  
Person.prototype.setName = function(value) {  
    this.name = value;  
};  
  
Person.prototype.getName = function() {  
    return this.name;  
};  
  
function Student(arg) {  
}  
  
var you = new Person("iamhjoo");  
Student.prototype = you;  
  
var me = new Student("zzoon");  
me.setName("zzoon");  
console.log(me.getName()); // zzoon

부모의 생성자가 호출되지 않으면, 인스턴스의 초기화가 제대로 이루어지지 않아 문제가 발생할 수 있다.


-> 부모 클래스의 생성자를 호출해야 한다.

function Student(arg) {
	Person.apply(this, arguments); // 새로운 Person 인스턴스(this가 인스턴스) 가 만들어 지는듯
}

자식 클래스의 인스턴스에 대해서도 부모 클래스의 생성자를 실행시킬 수 있다.


but 부모 클래스의 인스턴스와 자식 클래스의 인스턴스는 서로 독립적일 필요가 있다.

function Person(arg) {  
    this.name = arg;  
}  
  
Function.prototype.method = function(name, func) {  
    this.prototype[name] = func;  
};  
  
Person.method("setName", function(value) {  
    this.name = value;  
});  
  
Person.method("getName", function() {  
    return this.name;  
});  
  
function Student(arg) {  
}  
  
function F() {}  
F.prototype = Person.prototype;  
  
Student.prototype = new F();  
Student.prototype.constructor = Student;  
Student.super = Person.prototype;  
  
var me = new Student();  
me.setName("zzoon");  
console.log(me.getName());


상속 관계를 즉시 실행 함수와 클로저를 활용하여 최적화된 함수

var inherit = function(Parent, Child) {  
      
    var F = function() {};  
  return function(Parent, Child) {  
        F.prototype = Parent.prototype;  
  Child.prototype = new F();  
  Child.prototype.constructor = Child;  
  Child.super = Parent.prototype;  
  };  
  }();