개발/Java Script
ES6 Class, super
ksy0314
2020. 9. 9. 22:58
기존 상속
- prototype을 Object.create(부모 객체 prototype)을 사용해 속성과 메소드 가져오기
- constructor을 자신의 constructor로 변경하기
- 부모객체.call(this.name); 을 통해 this 전달시켜주기
- 부모객체.prototype.메소드이름.apply(this)와 같은 형식으로 부모 매소드 사용가능
ES6 Class를 사용하면
class Person {
constructor(name) {
this.name = name;
}
eat() {
console.log(this.name + " is eating.");
}
}
class Student extends Person {
constructor(name) {//
super(name); // Property를 따로 변경하지 않았기 때문에 생략 가능하다.
} //
eat() {
super.eat(); // 이건 Person.eat()을 가져오기에 override하려면 생략 가능
console.log(this.name+ “is studying.”);
}
learn() {
console.log(this.name+ “is coding.”);
}
}
var student1 = new Student("Daniel);
student1.eat();
// "Daniel is eating."
// "Daniel is studying."
모든것이 한방에 해결 완료
(동작원리는 같다.)