Questo perché prototype
è una proprietà della funzione di costruzione, non una proprietà di se stesso. Tuttavia, l'oggetto prototype
ha un riferimento al costruttore, in modo da poter accedere di prototype
un oggetto tramite la sua proprietà constructor
:
function Foo() {}
Foo.prototype.foo = "bar";
var c = new Foo;
console.log(c.constructor === Foo); // true
console.log(c.constructor.prototype); // { foo: 'bar' }
Tuttavia, questo non funzionerà se si sovrascrive il prototype
di proprietà iniziale della funzione di costruzione:
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); // {}
Ecco perché è meglio usare il nuovo metodo Object.getPrototypeOf
introdotto in ES5.
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' }
Un'altra soluzione sarebbe stata quella di fare in modo di ripristinare il riferimento constructor
sul prototipo:
function Foo() {}
// Overwriting the initial prototype
Foo.prototype = {
constructor: Foo, // restore the constructor reference
foo: "bar"
};
fonte
2012-04-26 08:44:36
Ottima spiegazione –
@TahaAhmad: Sono contento che abbia aiutato! –