jQuery的JavaScript OOP [英] JavaScript OOP with jQuery

查看:62
本文介绍了jQuery的JavaScript OOP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象myObject,内部有函数execute(),内部有$.ajax({,其中有complete: function(xmlHttp){.在该函数内部,我想调用在myObject中定义的setResult.该怎么做?

I have object myObject, inside I have function execute(), inside I have $.ajax({ which have complete: function(xmlHttp){. Inside that function I want to call setResult which is defined in the myObject. How to do that?

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对象.

The standard way to do OOP is to use myObject as a constructor, and extend its prototype object with whatever needs to be inherited.

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();

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

There's no requirement that it be done this way, but it's very common.

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

You need to keep in mind that the calling context of a function varies based on how that function is called. With respect to the complete: callback, jQuery sets the context, so it won't be your object unless you tell jQuery to make it that object or use some other way to bind the context.

jQuery的$.ajax方法为您提供了context:属性,该属性使您可以设置回调的调用上下文.

jQuery's $.ajax method gives you a context: property that lets you set the calling context of the callbacks, as I've shown above.

这篇关于jQuery的JavaScript OOP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆