我想在prototype链上创建一个设置对象,作为我的应用程序的查找。我试过这个:
http://jsfiddle.net/7kwXd/3/
var d9l = {};
d9l.aMethod = function() {
//fails here with Cannot read property 'dimension1' of undefined
alert(this.anObject.dimension1);
};
d9l.aMethod.prototype.anObject = {
dimension1 : "x1",
dimension2 : "y1"
};
var testing = d9l.aMethod();但是我只得到不能读取构造函数中未定义的的属性'dimension1‘。不能将原型定义为对象吗?
发布于 2013-11-01 15:14:55
因为d9l不是一个构造的对象,所以它的方法不像您所期望的那样引用this。要验证,请尝试alert(this)并查看您得到了什么。
要解决这个问题,请执行以下操作:
function d9l() {}
d9l.prototype.aMethod = function() {
alert(this.anObject.dimension1);
};
d9l.prototype.anObject = {
dimension1: "x1",
dimension2: "y1"
};
var testing = (new d9l()).aMethod();发布于 2013-11-01 15:17:41
prototype属性仅适用于构造函数( http://jsfiddle.net/7kwXd/2/):
var Ctor = function(){
}
Ctor.prototype = {
aMethod:function(){
alert(this.anObject.dimension1);
},
anObject:{
dimension1 : "x1",
dimension2 : "y1"
}
}
var d9l = new Ctor();
var testing = d9l.aMethod();这是一篇很好的关于原型如何工作的文章:http://msdn.microsoft.com/en-us/magazine/ff852808.aspx
https://stackoverflow.com/questions/19729560
复制相似问题