Last active
October 26, 2019 14:47
-
-
Save evan-moon/a7e5a51e20d22016ea443a03480765b7 to your computer and use it in GitHub Desktop.
Object.create 메소드 없이 상속 구현
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function SuperClass (name = 'name') { | |
this.name = name; | |
} | |
SuperClass.prototype.say = function () { | |
console.log(`Hi, I am ${this.name}`); | |
} | |
function SubClass (name) { | |
SuperClass.apply(this, [name]); | |
} | |
// Object.create 메소드가 없으므로 중간에 감춰진 생성자 함수를 하나 거쳐야 한다. | |
function Bridge () {} | |
Bridge.prototype = SuperClass.prototype; | |
// SubClass.prototype = new SuperClass();처럼 하게되면 | |
// SubClass.prototype 객체가 name 속성도 가져버리게 되고, SubClass 생성자 함수를 사용해서 생성된 객체가 이 속성을 모두 공유하게 되어버린다. | |
// 하지만 SuperClass 내에서 this.name을 선언할 때의 목적은 인스턴스 별로 해당 속성을 소유하게 하고자 함이었으므로, 결국 중간 브릿지 생성자 함수를 한번 거쳐야 한다. | |
SubClass.prototype = new Bridge(); | |
SubClass.prototype.constructor = SubClass; | |
const evan = new SubClass('Evan'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment