使用jQuery的JavaScript OOP

sve*_*ija 1 javascript oop jquery

我有对象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));
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

小智 6

执行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();
Run Code Online (Sandbox Code Playgroud)

没有要求以这种方式完成,但它很常见.

您需要记住,函数的调用上下文根据函数的调用方式而有所不同.关于complete:回调,jQuery设置上下文,因此它不会是你的对象,除非你告诉jQuery使它成为那个对象或使用其他方式来绑定上下文.

jQuery的$.ajax方法为您提供了一个context:属性,允许您设置回调的调用上下文,如上所示.