TIL14: OOP / Inheritance Patterns
객체지향 프로그래밍에서 Instantiation Patterns를 통해 '캡슐화'와 '추상화'에 대해 어느 정도 이해할 수 있게 되었습니다. 이번에는 Inheritance Patterns를 통해 '상속'과 '다형성'에 대해 살펴보겠습니다.

- Pseudoclassical에서 '상속'
우선 prototype chain 연결(Instance.__proto__ === Class.prototype)을 위해Object.create()메소드와 Human.prototype을 이용하여 Student.prototype을 생성합니다.
그런데 이 때 Student.prototype이 생성되는 과정에서 Student.prototype.constructor마저 Human.prototype.constructor를 참조해버리게 되므로 Student.prototype.constructor에 대해 Student객체를 참조함을 명시해야 합니다.
그리고 Student객체에 입력된 전달인자가 Human객체에 전달되고, Student객체에서도 Human객체의 메소드가 실행되도록 하기 위해Human()가 호출될 때call()이나apply()메소드를 사용하여 Student객체의 Execution Context인 "this"를 공유해야 합니다.
var Human = function(name) {
this.name = name;
}
Human.prototype.sleep = function() {
console.log('zzz');
};
var Student = function(name) {
// 3. Human 객체로부터 Student객체로 상속: Execution Context('this') 공유
Human.call(this, name);
// Human.apply(this, arguments);
};
// 1. prototype chain 연결
Student.prototype = Object.create(Human.prototype);
// 2. constructor 연결
Student.prototype.constructor = Student;
Student.protytype.learn = function() {
console.log('learning');
};
var steve = new Human('steve');
steve instanceof Human; // true
steve.__proto__ === Human.prototype; // true
steve instanceof Student; // false
steve.__proto__ === Student.prototype; // false
var john = new Student('john');
john instanceof Human; // true
john instanceof Student; // true
john.__proto__ === Student.prototype; // true
john.__proto__ === Human.prototype; // false
- Pseudoclassical에서 '다형성'
앞서 부모 객체와 자식 객체의 상속을 통해 속성 및 메소드가 전달될 수 있도록 프로토타입과 생성자함수 그리고 "this"에 관하여 그 관계를 명확히 하였습니다.
한편, 부모 객체의 메소드와 자식 객체의 메소드 실행 결과가 다르게 나타나도록 자식 객체의 메소드 기능을 확장할 수도 있는데, 이 때도 부모객체의 메소드 호출시 Execution Context 공유를 위해 마찬가지로call()이나apply()메소드를 사용합니다. 그런 다음 기능을 추가함으로써 다형성을 구현할 수 있습니다.
// 다형성 구현: 메소드 확장
Student.prototype.sleep = function() {
Human.prototype.sleep.call(this);
console.log('do not sleep');
};
var steve = new Human('steve');
steve.sleep(); // 'zzz'
steve.learn(); // TypeError
var john = new Student('john');
john.sleep(); // 'zzz' 'do not sleep'
john.learn(); // 'learning'
코드 및 자료 출처: 코드스테이츠(CodeStates)
Author And Source
이 문제에 관하여(TIL14: OOP / Inheritance Patterns), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@charlie-lyc/TIL14-OOP-Inheritance-Patterns저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)