//생성자 함수
function Circle(radius){
this.radius = radius;
}
// getArea 메서드를 공유해서 사용할 수 있도록 프로토타입에 추가한다.
// 프로토타입은 Circle 생성자 함수의 prototype 프로퍼티에 바인딩되어 있다.
Circle.prototype.getArea = function (){
return Math.PI * this.radius ** 2;
};
//인스턴스 생성
const circle1 = new Circle(1);
const circle2 = new Circle(2);
//Circle 생성자 함수가 생성하는 모든 인스턴스는 하나의 getArea 메서드를 공유한다.
console.log(circle1.getArea === circle2.getArea); //true
모든 객체는 하나의 프로토타입을 갖고 있으며 __prototype__
접근자 프로퍼티를 통해 자신의 프로토 타입, [[prototype]] 내부 슬롯에 간접적으로 접근할 수 있다.
prototype 프로퍼티는 함수 객체만이 소유하며 생성자 함수가 생성할 인스턴스(객체)의 프로토타입을 가리킨다. 따라서 생성자 함수로서 호출할 수 없는 함수, 즉 non-consturctor 인 화살표 함수, 메서드 축약 표현으로 정의한 메서드는 prototype 프로퍼티를 소유하지 않으며 프로토타입도 생성하지 않는다.
모든 프로토타입은 constructor 프로퍼티를 갖는다. 이 constructor 프로퍼티는 prototype 프로퍼티로 자신을 참조하고 있는 생성자 함수를 가리킨다.
// 생성자 함수
function Person(name){
this.name = name;
}
const me = new Person("Lee");
console.log(me.constructor === Person); //true
const obj = new Object();
console.log(obj.constructor === object); // true
const add = new Function("a", "b", "return a + b");
console.log(add.constructor === Function); //true
// 함수 정의(constructor)가 평가되어 함수 객체를 생성하는 시점에 프로토타입도 더불어 생성된다.
console.log(Person.prototype); // {constructor : f}
function Person(name){
this.name = name;
};