- 자바스크립트는 프로토타입 기반 언어
- 클래스 기반 언어에서는 '상속'을 사용
- but, 프로토타입 기반 언어에서는 어떤 객체를 원형(prototype)으로 삼고
이를 복제(참조)함으로써 상속과 비슷한 효과를 얻음
var instance = new Constructor();
▶어떤 생성자 함수(Constructor)를 new 연산자와 함께 호출하면
▶ Constructor에서 정의된 내용을 바탕으로 새로운 인스턴스(instance)가 생성됨
▶ 이때 instance에는 __proto__ 라는 프로퍼티가 자동으로 부여
▶ 이 프로퍼티는 Constructor의 prototype이라는 프로퍼티를 참조
constructor 프로퍼티
: 생성자 함수의 프로퍼티인 prototype 객체 내부와 인스턴스의 __proto__ 객체 내부에는 constructor라는 프로퍼티가 존재
: 원래의 생성자 함수(자기 자신) 참조
=> 인스턴스로부터 그 원형이 무엇인지를 알 수 있는 수단
var arr = [1, 2];
Array.prototype.constructor === Array // true
arr.__proto__constructor === Array // true
arr.constructor === Array // true
var arr2 = new arr.constructor(3, 4);
console.log(arr2); // [3, 4]
[Constructor]
[instance].__proto__.constructor
[instance].constructor
Object.getPrototypeOf([instance]).constructor
[Constructor].prototype.constructor
[Constructor].prototype
[instance].__proto_
[instance]
Object.getPrototypeOf([instance])
프로토타입 체인
: 어떤 데이터의 _proto__ 프로퍼티 내부에 다시 _proto__가 연쇄적으로 이어진 것
프로토타입 체이닝 이 체인을 따라가며 검색하는 것
var Arr = [1, 2];
Array.prototype.toString.call(arr); // 1, 2
Object.prototype.toString.call(arr); // [Object Array]
arr.toString(); // 1, 2
arr.toString = function () {
return this.join('_');
};
arr.toString(); // 1_2
기본적으로 모든 객체의 __proto__에는 Object.prototype이 연결됨
어떤 생성자 함수이든 prototype은 반드시 객체이기 때문에 Obeject.prototype이 언제나 프로토타입 체인의 최상단에 존재하게 됨
=> 객체에서만 사용할 메서드를 Object.prototype 내부에 정의한다면 다른 데이터 타입도 해당 메서드를 사용할 수 있게 되기 때문에 다른 데이터 타입처럼 프로토타입 객체 안에 정의할 수 없음
ex) Object.freeze()
=> 따라서, Object.prototype에는 어떤 데이터에서도 활용할 수 있는 범용적인 메서드들만 있음
ex) toString, hasOwnProperty