class Elf {
constructor(name, weapon) {
this.name = name;
this.weapon = weapon;
}
attack() {
reutrn 'atack with' + this.weapon;
}
}
const fiona = new Elf('Fiona', 'ninja stars');
const orge = {...fiona}
ogre.__proto__
// {}
fiona.__proto__
// Elf{}
- 얕은 복사로 orge를 만들었다. orge와 fiona는메모리상 다른 곳에 저장되어 있는 별개의 객체이다. orge는 Elf의 prototype 상속을 받지 못한다.
class 상속
class Character {
constructor(name, weapon) {
this.name = name;
this.weapon = weapon;
}
attack() {
reutrn 'atack with' + this.weapon;
}
}
class Elf extends Character{
constructor(name,weapon,type) {
super(name, weapon)
this.type = type;
}
}
extends: subclass 만들기
- extends를 사용: Character 클래스의 모든 메소드와 프로퍼티를 상속받는 subclass를 만들고 싶다.
super: super class의 constructor 호출
- super는 상위 객체의 함수를 호출할 때 사용된다.
- subclass의 constructor를 만들고 this 키워드를 쓰고 싶을 때 super()를 subclass의 constructor안에서 호출해야한다.
- super()를 호출하면 super-class를 호출(super-class의 constructor)
- class Elf extends Character: Elf의 프로토타입 체인이 Character과 연결된다.
- 만약 Elf의 인스턴스가 가지고 있는 메소드가 없을 경우 프로토타입 체인을 타고 Character에서 찾는다.
- if we want to set any sort of property that is used the this keyword we have to call super => call the constructor of our sueprclass and after that, i'll know what to do with this keyword
Orge.prototype.makeFort()
- JS created this for us bucause we used class keyword and
console.log(Ogre.prototype.isPrototypeOf(shrek))
//true
console.log(Character.prototype.isPrototypeOf(Ogre.prototype))
//true
- Ogre는 생성자 함수
- inheritance in js doesn't actually copy our functionality it simply links up the prototype chain