Javascript는
프로토타입 기반 언어
로 여기서 프로토타입은원형 객체
를 의미한다.
__proto__
가 Function.prototype객체
니까 근본이 객체인거고class Human {
constructor(name, age) {
this.name = name;
this.age = age;
}
sleep() {
console.log(`${this.name}은 잠에 들었습니다`);
}
}
let kimcoding = new Human('김코딩', 30);
let moon = new Human('moon', 10);
Human.prototype.constructor === Human // true
Human.prototype === kimcoding.__proto__ // true
kimcoding.__proto__ === moon.__proto__ // true
Human.prototype.sleep === kimcoding.sleep // true
Human.prototype.sleep === moon.sleep // true
kimcoding.sleep === moon.sleep // true
Human.prototype.sleep === kimcoding.sleep === moon.sleep // false
Object.prototype === Human.__proto__.__proto__ // true
// 결론적으로 Object => Function => class Human
클래스 Human과 인스턴스 steve, 프로토타입의 관계
우리가 흔히 쓰는 배열 역시 원리가 동일!
배열(arr)은 Array 클래스의 인스턴스이며, 프로토타입에는 다양한 메서드가 존재
JavaScript에서 객체 지향 프로그래밍 특성 중
상속
을 구현하기 위해프로토타입 체인
을 사용한다.
class Human {
constructor(name, age) {
this.name = name;
this.age = age;
}
sleep() {
console.log(`${this.name}은 잠에 들었습니다`);
}
}
class Student extends Human {
constructor(name, age, grade) {
super(name, age)
this.grade = grade;
}
study(num) {
this.grade = this.grade + num;
return `${this.name}의 성적이 ${num}만큼 올라 ${this.grade}이 되었습니다.`
}
}
let mincoding = new Student('민학생', 19, 70);