我有这个简单的Javascript对象,它在一个本地方法中调用自己的原型方法。 [看我的编辑]
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'
。
知道应该怎么做吗?
编辑: 哎呀,刚才意识到我从来没有打过内心(),但感谢帕特里克回答这个部分。这是一个更好的例子
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'
答案 0 :(得分:3)
test.exported();
而不是
Obj.exported();
您应该在exported()
对象上调用test
方法,而不是在Obj
构造函数上调用。
<强>更新强>
到达function inner(){...}
内部后。 this
是指全局window
而非Obj
,因此从this
传递实际对象inner(this)
并从该传递的对象调用export()
function inner(cthis){...}
,类似于。
function inner(cthis) {
//----------^--get Obj on here
cthis.exported();
}
this.exported2 = function() {
inner(this);
//------^--pass Obj from here
};
答案 1 :(得分:2)
要调用导出,您需要将其分配给您指定实例的变量:
test.exported();
同样对于inner
函数,您无法使用this
来访问Obj对象,因为它引用window
。
保存对this
的引用,然后使用它来调用函数
var Obj = function() {
var _this = this;
function inner() {
_this.exported();
}
this.exported = function() {
alert("yay!");
};
};