我有对象myObject
,里面我有函数execute()
,里面我有$.ajax({
其中有complete: function(xmlHttp){
。在该函数内部我想调用 setResult ,它是在myObject
。怎么做?
function myObject() {
this.setResult = setResult;
function setResult(result) {
this.result = result;
}
function execute() {
$.ajax({
complete: function(xmlHttp){
(?) setResult(jQuery.parseJSON(xmlHttp.responseText));
}
});
}
进行 OOP 的标准方法是使用myObject
作为构造函数,并扩展它的prototype
具有任何需要继承的对象。
function myObject() {
// constructor function
}
myObject.prototype.setResult = function (result) {
this.result = result;
}
myObject.prototype.execute = function() {
$.ajax({
context: this, // bind the calling context of the callback to "this"
complete: function(xmlHttp){
this.setResult(jQuery.parseJSON(xmlHttp.responseText));
}
});
}
var obj = new myObject();
obj.execute();
没有要求这样做是很常见的。
您需要记住,函数的调用上下文根据该函数的调用方式而变化。相对于该complete:
回调,jQuery 设置上下文,因此它不会是您的对象,除非您告诉 jQuery 将其设为该对象或使用其他方式绑定上下文.
jQuery 的$.ajax
方法给你一个context:
属性可让您设置回调的调用上下文,如我上面所示。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)