代码剪切下面抛出一个错误TypeError: myObj.prototype is undefined
.有人能解释我为什么吗?
为什么没有prototype
对new Object()
与对象文本如下规定?
var myObj = { a : "This is a", b : "This is b" } myObj.prototype.c= "This is c"; // TypeError: myObj.prototype is undefined
如果这不是有效的方法,那么我该如何实现呢?
在早期版本的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
是类型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?
看到它在行动.