prototype
객체JavaScript 의 모든 객체는 부모 역할을 담당하는 prototype
이라는 객체를 가지고 있다.
객체 지향의 상속 개념과 비슷하게 부모인 prototype
의 프로퍼티, 메소드를 상속받아 사용할 수 있다.
지금까지 arr.push()
, arr.slice()
등과 같이 배열 자체에 메소드를 붙여 사용했다. arr
자체에 .push()
나 .slice()
같은 메소드가 없는데도 문제없이 사용할 수 있었던 이유는 arr
부모에게 메소드를 arr
이 상속받았기 때문이다.
.__proto__
프로퍼티객체의 입장에서 자신의 부모 역할을 하는, 자기가 생성될 때 참조한 프로토타입 객체를 가리킨다.
class
함수 Human
class Human {
constructor(name, age) {
[this.name](http://this.name/) = name;
this.age = age;
}
sleep() {
console.log(`${this.name}은 잠에 들었습니다`);
}
}
class
함수 Human
의 (생성자 함수에 의해 생성된) 인스턴스 객체 kimcoding
let kimcoding = new Human('김코딩', 30);
console.log(kimcoding);
Human {name: '김코딩', age: 30}
age: 30
name: "김코딩"
[[Prototype]]: Object
constructor: class Human
sleep: ƒ sleep()
[[Prototype]]: Object
console.log(kimcoding.__proto__);
Human
의 prototype
에 접근했음
.prototype
프로퍼티생성자 함수나 클래스 함수에 의해 생성된 객체의 부모의 프로토타입 객체를 가리킨다.
class
함수 Human
class Human {
constructor(name, age) {
[this.name](http://this.name/) = name;
this.age = age;
}
sleep() {
console.log(`${this.name}은 잠에 들었습니다`);
}
}
class
함수 Human
의 (생성자 함수에 의해 생성된) 인스턴스 객체 kimcoding
let kimcoding = new Human('김코딩', 30);
console.log(kimcoding);
Human {name: '김코딩', age: 30}
age: 30
name: "김코딩"
[[Prototype]]: Object
constructor: class Human
sleep: ƒ sleep()
[[Prototype]]: Object
console.log(Human.prototype);
Human
의 prototype
에 접근했음
.constructor
프로퍼티prototype
객체는 .constructor
라는 프로퍼티를 갖는다. .constructor
프로퍼티는 객체의 입장에서 자신을 생성한 객체를 가리킨다. 위의 프로퍼티들은 모두 함수의 prototype
을 가리켰지만 이건 정말 객체를 가리킨다.
console.log(kimcoding.constructor);
console.log(kimcoding.__proto__.constructor);
console.log(Human.constructor);
console.log(Human.prototype.constructor);
자바스크립트는 특정 객체의 프로퍼티나 메소드에 접근할 때 자신의 객체뿐만 아니라 __proto__
가 가리키는 링크를 따라서 자신의 부모 프로토타입 객체의 프로퍼티나 메소드에 접근할 수 있다.
특정 객체의 프로퍼티나 메소드에 접근했을 때 그 객체에 해당 프로퍼티, 메소드가 존재하지 않는다면, __proto__
가 가리키는 링크를 따라 부모 프로토타입 객체의 프로퍼티나 메소드를 차례로 검색하는 것이 프로토타입 체인이다.
프로토타입 체이닝의 끝은 Object.prototype
이다.
정확히 하위 객체는 상위 객체의 프로퍼티나 메소드를 상속받는 게 아니라 공유한다고 볼 수 있다.
프로토타입 체이닝은 해당 객체에 없는 프로퍼티, 메소드에 접근했을 때 일어난다.
혹시나 잘못된 정보가 있다면 댓글로 알려주세요 ! 저의 성장의 큰 도움이 될 것 같습니다.🌱