728x90
반응형
프로토타입 체인
자바스크립트에서는 객체는 자신만의 속성과 메소드를 갖고 있다. 객체의 어떤 속성에 접근하려할 때 그 객체 자체 속성 뿐만 아니라 객체의 프로토타입, 그 프로토타입의 프로토타입 등 프로토타입 체인의 종단에 이를 때까지 그 속성을 탐색한다. 이처럼 프로토타입이 계속해서 연결되어 있어 프로토타입 체인이라고 부른다.
extends와 super 키워드를 사용하여 상속하는 방법
class Human {
constructor(name, age, height, weight) {
this.name = name;
this.age = age;
this.height = height;
this.weight = weight;
}
greeting() {
console.log(`Hi I'm ${this.name}.`);
}
}
let john = new Human("John", 23, 185, 80);
john.greeting() //Hi I'm John.
Human클래스를 Student 클래스에 상속
class Student extends Human { //extends 키워드를 이용하여 상속
constructor(name, age, height, weight, grade) {
super(name, age, height, weight); // super키워드를 통해서 상속받은 속성을 사용
this.grade = grade;
}
}
let alex = new Student("Alex", 21, 170, 65, "college");
alex.grade;
alex.greeting();
.prototype
부모 클래스의 속성과 메소드를 탐색할 때 사용된다.
Human.prototype;
/*
{constructor: ƒ, greeting: ƒ} // Human 클래스 위의 프로토타입이 없음, 조상 클래스만 존재
constructor: class Human
greeting: ƒ greeting()
[[Prototype]]: Object // 조상 클래스 Object
*/
Student.prototype;
/*
Human {constructor: ƒ} // Human 클래스가 프로토타입
constructor: class Student
[[Prototype]]: Object // 조상 클래스 Object
*/
.proto
자식 클래스에서 직속 부모의 프로토타입을 탐색할 때 사용한다.
Student.__proto__;
/*
직속 부모의 프로토타입을 출력
class Human {
constructor(name, age, height, weight) {
this.name = name;
this.age = age;
this.height = height;
this.weight = weight;
}
greeting() {
console.log(`Hi I'm ${this.name}.`);
}
}
*/
HTMLDivElement.__proto__; // ƒ HTMLElement() { [native code] }
HTMLDivElement.__proto__.__proto__; // ƒ Element() { [native code] }
HTMLDivElement.__proto__.__proto__.__proto__; // ƒ Node() { [native code] }
HTMLDivElement.__proto__.__proto__.__proto__.__proto__; // ƒ EventTarget() { [native code] }
Object
Object는 모든 클래스의 조상이다. 즉, 최상위 부모 클래스이다.
728x90
반응형
'JavaScript' 카테고리의 다른 글
[JavaScript] Promise (0) | 2022.05.31 |
---|---|
[JavaScript] 비동기 (0) | 2022.05.27 |
[JavaScript] 프로토타입 (0) | 2022.05.26 |
[JavaScript] 객체 지향 프로그래밍 (0) | 2022.05.26 |
[JavaScript] 클래스와 인스턴스 (0) | 2022.05.25 |