Javascript类澄清
请把代码通读一遍Javascript类澄清,javascript,class,Javascript,Class,请把代码通读一遍 function Item() { this.state = 0; } Item.prototype.SendRequest = function() { //some request callback returns and calls GotResult var that = this; { that.GotResult();//used 'that' because its inside another block } } Item.prototy
function Item()
{
this.state = 0;
}
Item.prototype.SendRequest = function()
{
//some request callback returns and calls GotResult
var that = this;
{
that.GotResult();//used 'that' because its inside another block
}
}
Item.prototype.GotResult = function()
{
//add to local db with callback which calls AddedToLocalDb
var that = this;
// Here is where the problem is
{
that.AddedToLocalDb();//..... ERROR
}
}
Item.prototype.AddedToLocalDb = function()
{
}
在“this.AddedToLocalDb()”上,我得到了它的未定义。为什么呢?有什么想法吗?
在该块上,“this”变量未定义。我是否犯了错误或存在范围问题。任何帮助都将不胜感激。这很可能是回调函数的问题,调用回调函数时,
此
值丢失。但是为了确定,您必须显示涉及回调的实际代码。我们不仅需要查看方法定义,还需要查看使用这些方法导致问题的实际代码
我怀疑这是您调用并将GotResult
传递给的东西。如果这个猜测是正确的,那么您可以传递this.GotResult.bind(this)
,而不只是传递this.GotResult
,它可能会解决您的问题
这种类型的问题有时可以通过var解决,它=这项
技术,但这只在同一范围内使用本地函数时有效,而不是在同级范围内定义方法定义时有效。顺便说一句,我添加了gotreult.bind(那项);