Nelle versioni precedenti di EcmaScript non era possibile accedere direttamente al prototipo di oggetti; la proprietà prototype
esisteva solo sulle funzioni e entra in gioco quando vengono utilizzate come costruttori. Così si potrebbe fare questo:
// This is the myObj constuctor
function myObj() {
this.a = "This is a";
this.b = "This is b";
}
// Setting a property on the constructor prototype
// All instances will share this
myObj.prototype.c= "This is c";
// Creating a new object and testing its "c" property
var obj = new myObj();
alert(obj.c); // "This is c"
Modern browsers attuare Object.getPrototypeOf
, il che significa che si può fare questo:
var myObj = {
a : "This is a",
b : "This is b"
}
Object.getPrototypeOf(myObj).c= "This is c";
Tuttavia, bisogna stare attenti! Se si esegue questa operazione, quindi tutti gli oggetti che esistono ora e tutti gli oggetti che vengono creati in futuro erediteranno la proprietà c
attraverso la loro catena di prototipi!
Questo perché myObj
è di tipo Object
, e il prototipo di Object
viene ereditato da tutto ciò che è un oggetto di qualsiasi tipo. Questo porta a:
var myObj = {
a : "This is a",
b : "This is b"
}
Object.getPrototypeOf(myObj).c= "This is c";
var anotherObject = {};
alert(anotherObject.c); // "This is c" -- was it expected?
See it in action.
Dovrebbe essere solo 'myObj.c =" foo ";' – epascarello
È possibile ottenere il prototipo da un'istanza con Object.getPrototypeOf: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/getPrototypeOf anche se in questo caso probabilmente non lo si vorrebbe. –
Dai un'occhiata a [Eloquent Javascript] (http://eloquentjavascript.net/chapter8.html). –