pseudoclassical은 변수에 함수를 할당해서 constructor를 만든다. 매개변수가 있는경우도 있고 없을 수도 있다.
let Developer = function(name, subject){
this.name = name;
this.career = 2;
this.hasMac = false;
this.subject = subject;
}
Being.prototype.make = function(){};
Being.prototype.communication = function(){};
let spring = new Developer("spring", "javascript");
이 코드는 매개변수가 있는 경우의 예이다. 메소드는 변수와 prototype을 이용해서 할당한다. new연산자를 사용해서 새로운 instance를 만들어서 사용이 가능하다.
let Spring = function(name, subject){
Developer.call(this, subject);
this.name = "spring";
this.job = "programmer";
this.colleague = "kim";
}
Spring.prototype = Object.create(Developer.prototype);
Spring.prototype.constructor = Spring;
Spring.prototype.conference = function(){
return "회의시간입니다";
};
위에서 만든 Developer을 superClass로 해서 Spring이라는 instance를 만들었다. 부모의 코드를 그대로 가져오면서 this의 바인딩을 하기위해 call을 이용한다. 부모코드중에 변경될 부분만 적어주고 추가할 프로퍼티들도 같이 적는다.
여기서 조심해야 할 과정은 부모의 메소드를 사용하기 위해 Object.create메소드를 사용하는 것이다. Object.create는 부모의 메소드를 복사해서 Spring에서 사용가능하도록 해준다. 하지만 이 메소드의 문제점은 Object.create와 constructor의 연결을 끊어지게 만든다는 것이다. 이것을 해결하기 위해 Spring.prototype.constructor = Spring; 이 코드를 꼭! 적어서 재연결을 하고 사용해야 한다는 것이다.
ES6의 class는 pseudoclassical의 단점을 보안하기 위해서 나왔다.
class Developer {
constructor(name, subject) {
this.name = name;
this.career = 2;
this.hasMac = false;
this.subject = subject;
}
make(){}
communication(){}
}
let spring = new Developer("spring", "javascript");
위의 함수가 class를 적용한 모습이다. constructor에 변수를 지정하고 메소드는 prototype을 사용하지 않고 class안에 적어준다.
class Spring {
constructor(subject){
super(subject);
this.name = "spring";
this.job = "programmer";
this.colleague = "kim";
}
conference(){return "회의시간입니다";}
}
이렇게 간단하게 상속이 이루어진다.