在早期版本的 EcmaScript 中,您不能直接访问对象的原型;该prototype
属性仅存在于函数上,当它们用作构造函数时它就会发挥作用。所以你可以这样做:
// 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"
现代浏览器实现Object.getPrototypeOf
,这意味着您可以这样做:
var myObj = {
a : "This is a",
b : "This is b"
}
Object.getPrototypeOf(myObj).c= "This is c";
但是,您必须小心!如果这样做,那么现在存在的所有对象以及将来创建的所有对象都将c
通过其原型链继承该属性!
这是因为myObj
is 的 type Object
,并且 的原型被任何类型Object
的对象所继承。这将导致:
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?
看到它在行动。