In earlier versions of EcmaScript you could not directly access the prototype of objects; the prototype
property existed only on functions, and it comes into play when they are used as constructors. So you could do this:
// 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 implement Object.getPrototypeOf
, which means you can do this:
var myObj = {
a : "This is a",
b : "This is b"
}
Object.getPrototypeOf(myObj).c= "This is c";
However, you have to be careful! If you do this, then all objects that exist now and all objects that get created in the future will inherit the property c
through their prototype chain!
This is because myObj
is of type Object
, and the prototype of Object
is inherited by everything that is an object of any type. This leads to:
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.