标题有点怪异,不太清楚句子中解释它的最佳方式...JavaScript范围 - 通过回调已定义的函数
目前有一个有3个函数的对象; func,funcSuccess和funcFailure。 func包含一个jQuery ajax请求,其中this.funcSuccess作为成功回调函数,funcError作为错误回调函数。 func通过一个回调函数传回任何成功值,但是这个回调函数需要在funcSuccess代码中执行。
下面的代码:
var Obj =
{ func: function (callback) {
$.ajax(
{ type: 'POST'
, url: '/func'
, success: this.funcSuccess
, error: this.funcError
}
)
}
, funcSuccess: function (res) {
// THIS IS WHERE CALLBACK IS NEEDED
callback(res.thing)
}
, funcError: function (res) {
debug(res)
}
}
我不知道是否有一个整洁的方式做到这一点,而不是:
var that = this
$.ajax(
{ type: 'POST'
, url: '/func'
, success: function (res) {
that.funcSuccess(res)
}
, error: this.funcError
}
)
肯定我失去了一些东西很明显,只是不太与它今天...
这没什么帮助,''callback'在'funcSuccess'中仍然是'undefined' - 你需要在那里明确地传递它。 – Bergi