은 그 자체의 속성이 아니기 때문에 생성자 함수의 속성이기 때문에 p
의 생성자 프로토 타입을 검색 할 수 있습니다. 그러나, prototype
객체는 생성자에 대한 참조를 가지고, 그래서 당신은 객체의 prototype
의 constructor
속성을 통해 액세스 할 수 있습니다 : 당신은 생성자 함수의 초기 prototype
속성을 덮어 쓸 경우
function Foo() {}
Foo.prototype.foo = "bar";
var c = new Foo;
console.log(c.constructor === Foo); // true
console.log(c.constructor.prototype); // { foo: 'bar' }
그러나이 작동하지 않습니다 :
function Foo() {}
// I overwrite the prototype property, so I lose the initial reference
// to the constructor.
Foo.prototype = {
foo: "bar"
};
var c = new Foo;
console.log(c.constructor === Foo); // false
console.log(c.constructor === Object); // true
console.log(c.constructor.prototype); // {}
그런 이유로 ES5에서 도입 된 새로운 Object.getPrototypeOf
방법을 사용하는 것이 좋습니다.
function Foo() {}
Foo.prototype = {
foo: "bar"
};
var c = new Foo;
console.log(c.constructor === Foo); // false
console.log(c.constructor === Object); // true
console.log(c.constructor.prototype); // {}
console.log(Object.getPrototypeOf(c)); // { foo: 'bar' }
또 다른 해결책은 당신이 프로토 타입에 constructor
참조를 복원 확인했을 것이다 :
function Foo() {}
// Overwriting the initial prototype
Foo.prototype = {
constructor: Foo, // restore the constructor reference
foo: "bar"
};
우수 설명 –
@TahaAhmad : 도와 줘서 기뻐요! –