class를 이용해서 상속기능을 구현해보자.
class parent {
constructor(){
this.name = "bora";
}
}
const child = new parent();
// class로 부모함수의 이름 지정 후 안쪽에 constructor를 만들어주기
: 자식들이 직접 함수를 가지게됨
class parent {
constructor(){
this.name = "bora";
this.sayHi = function(){console.log("Hi")} // 이렇게
}
}
: 부모의 prototype에만 추가됨
class parent {
constructor(){
this.name = "bora";
}
sayHi(){ // 이렇게
console.log("Hi")
}
}
: constructor에 추가해주면 됨
class parent {
constructor(name, age){ // 이렇게
this.name = name;
this.age = age;
}
sayHi(){
console.log("Hi")
}
}
const child = new parent("bora", 29);
프로토타입을 출력할 때, a.__proto__ 말고 Object.getPrototypeOf(a)로도 확인 가능하고, 훨씬 직관적이라 쓰기 편함.