我有一个简单的 Javascript 对象,它在其本地方法之一中调用自己的原型(prototype)方法。 [查看我的编辑]
var Obj = function() {
function inner() {
this.exported();
}
this.exported = function() {
alert("yay!");
};
};
var test = new Obj();
Obj.exported();
但是,我收到错误 TypeError: Object function() {...} has no method 'exported'
。
知道该怎么做吗?
编辑: 哎呀,刚刚意识到我从未调用过 inside(),但无论如何还是感谢帕特里克回答了这一部分。这是一个更好的例子
var Obj = function() {
this.exported = function() {
inner();
};
function inner() {
this.yay();
}
this.yay = function() {
alert("yay!");
};
};
var test = new Obj();
test.exported();
我得到TypeError: Object [object global] has no method 'exported'
最佳答案
应该使用
test.exported();
而不是
Obj.exported();
您应该通过 test
对象调用 exported()
方法,而不是通过 Obj
构造函数。
更新
到达function inside(){...}
内部后。 this
是指全局 window
而不是 Obj
,因此从 inner(this) 传递实际对象
并从传递的对象中调用 this
)export()
到 function inside(cthis){...}
中,类似这样。
function inner(cthis) {
//----------^--get Obj on here
cthis.exported();
}
this.exported2 = function() {
inner(this);
//------^--pass Obj from here
};
关于Javascript 使用 this.function 会导致 'has no method' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22429986/