最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript OOP with jQuery - Stack Overflow

programmeradmin1浏览0评论

I have object myObject, inside I have function execute(), inside I have $.ajax({ which have plete: 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({
            plete: function(xmlHttp){
                (?) setResult(jQuery.parseJSON(xmlHttp.responseText));
            }
        });
    }

I have object myObject, inside I have function execute(), inside I have $.ajax({ which have plete: 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({
            plete: function(xmlHttp){
                (?) setResult(jQuery.parseJSON(xmlHttp.responseText));
            }
        });
    }
Share Improve this question asked Mar 11, 2012 at 19:37 svenkapudijasvenkapudija 5,16615 gold badges71 silver badges99 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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"
        plete: 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 mon.

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 plete: 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's $.ajax method gives you a context: property that lets you set the calling context of the callbacks, as I've shown above.

function myObject() {
    var that = this; // Reference to this stored in "that"
    this.setResult = setResult;

    function setResult(result) {
        this.result = result;   
    };

    function execute() {
         $.ajax({
            plete: function(xmlHttp){
                that.setResult(jQuery.parseJSON(xmlHttp.responseText));
        }
    });
}

Also you can check out jquery proxy and/or bind

发布评论

评论列表(0)

  1. 暂无评论