본문 바로가기

Dev-/java script, jQuery, Ajax

자바스크립트 상속 메서드

let inherit =  (function() {
function F() {}

return function(Parent, Child) {
F.prototype = Parent.prototype;

Child.prototype = new F();
Child.prototype.constructor = Child;
Child.super = Parent.prototype;
};
})();

1. prototype을 이용하는 기본 원리는 같지만, 중개자 F를 둬서 부모와 자식을 분리

2. 클로저, 즉시실행함수를 사용해 중개자 F를 1번만 생성

3. super라는 매개변수를 임의로 만들어 부모타입 명시





여기서, 

1. <중개자 F를 둬서 부모와 자식을 분리>를 자세히 보면


중개자 F를 두지 않았을 때

function Parent(name) { this.name = name; }
function Child() {}

let parent = new Parent('parent-name');
Child.prototype = parent;


/**
* Child.prototype ----> parent(Parent.prototype) -----> parent.__proto__(Parent)
* : 위와같이 Child의 prototype이 최종적으로 Parent를 가리키므로 아래와 같은 문제가 발생한다.
*/

Child.prototype.newCustomMethod = function() { console.log('Parent에는 추가되면 X!!!'); };
parent.newCustomMethod();

Child 클래스에만 추가하고 싶은 newCustomMethod함수가 있을때,

부모 클래스에도 추가되어버리는 문제가 발생한다.


실행도 잘 된다.




하지만 중개자 F를 두면 위와 같은 문제를 해결 할 수 있다.


중개자 F를 두어도, 자식 클래스.prototype.constructor가 부모 클래스.prototype.constructor를 가리키기 때문에,

명시적으로 자신의 constructor로 다시 바꿔준다.

(cf. 함수의 prototype 프로퍼티 --> new로 호출될 객체를 가리킴)











사실 잘 이해가 안되는 부분이 많다.


중개자 F를 만들어 new F()을 자식.prototype에 할당해주고,

다시 자식 클래스의 생성자를 자기껄로 바꿔주는 원리인데,,


사실 이게,, 

버릴 부모 객체 1개를 새로 생성해서 new Person()을 할당해주는거나 뭐가 다른건지 잘 모르겠다.