class Person {
// 생성자
constructor(name) {
this.name = name;
}
// 프로토타입 메서드
sayHi() {
console.log(`Hi ${this.name}`);
}
// 정적 메서드
static sayHello() {
console.log("HIHI");
}
}
// 인스턴스 생성
const me = new Person("Lee");
// 인스턴스의 프로퍼티 참조
console.log(me.name) // Lee
// 정적 메서드 호출
Person.sayHello();
// 프로토타입 메서드 호출
me.sayHi();
호이스팅이 안일어나는 것 처럼 작동하지만, 실제로는 호이스팅이 일어난다.
class Person2 {
constructor(name) {
// 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩된다.
console.log(this);
console.log(Object.getPrototypeOf(this) === Person2.prototype); // true
// 2. this에 바인딩되어있는 인스턴스를 초기화한다.
this.name = name;
// 3. 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다.
}
}
인스턴스 프로퍼티는 constructor 내부에서 정의해야 한다.
상속에 의한 클래스 확장은 기존 클래스를 상속받아 클래스를 확장하여 정의하는 것이다.
class Animal {
constructor(age, weight) {
this.age = age;
this.weight = weight;
}
eat() {
return "eat";
}
move() {
return "move";
}
}
class Bird extends Animal {
fly() {
return "fly";
}
}
const bird = new Bird(1, 5);
console.log(bird);
console.log(bird instanceof Bird);
console.log(bird instanceof Animal);
console.log(bird.eat());
console.log(bird.move());
console.log(bird.fly());