subclassing 패턴 중 pseudoclassical 방식에 대하여 알아보았다.
하지만 es6이후 class 문법이 추가되면서 전의 복잡한 방식을 하지 않아도
간단히 객체지향 프로그래밍을 구현할 수 있다.
class
function Human(name) {
this.name = name
};
Human.prototype.sleep = function () {
return `${this.name} zzzz`
};
function Student(name) {
Human.call(this,name) // call 메서드로 this를 전달
};
Student.prototype = Object.create(Human.prototype) // prototype 연결
Student.prototype.constructor = Student // constructor 연결
Student.prototype.learn = function () {};
let reo = new Student('yuchang');
reo.learn();
reo.sleep();
pseudoclassical 방식이다.
prototype을 연결해주고 constructor를 명시해준 뒤
생성자 함수 안에서 call 메서드로 this를 전달해주며 객체지향 프로그래밍을 구현하였다.
굉장히 복잡하다.
이제 class를 이용한 방식을 보며 비교해보자.
class Human {
constructor(name) {
this.name = name;
}
sleep() {
return `${this.name} zzzz`;
}
}
class Student extends Human { // extends로 상속을 해준다.
constructor(name) {
super(name); // context를 공유해준다.
}
learn() {};
}
let reo = new Student('yuchang');
reo.learn();
reo.sleep(); // yuchang zzzz
이처럼 pseudoclassical 방식보다 간결하게 상속을 구현할 수 있다.
여기서 extends는 Human으로부터 상속을 받아온다는 의미이고
super는 부모와 부모의 constructor를 불러오는데 쓰이는 것이다.
super에는 두 가지 용법이 있다.
super() // Human의 constructor를 가리킨다.
()를 쓰고 super 를 부르면 생성자를 가리키며
super.sleep() // Human을 가르킨다.
super를 .을 통해 호출하듯이 사용하면 클래스 자체를 가리킨다.
'Javascript' 카테고리의 다른 글
javascript async / await (0) | 2021.02.10 |
---|---|
javascript Promise (0) | 2021.02.04 |
javascript Object Oriented Programming (js-prototype) (0) | 2021.01.19 |
javascript Object Oriented Programming (0) | 2021.01.17 |
javascript this -명백한 바인딩(call, apply, bind) 호출 (0) | 2021.01.16 |
댓글