Scoping problem with Javascript callback

前端 未结 3 1492
眼角桃花
眼角桃花 2021-01-24 11:28

I am having some trouble getting a callback function to work. Here is my code:

SomeObject.prototype.refreshData = function()
{
  var read_obj = new SomeAjaxCall         


        
3条回答
  •  旧时难觅i
    2021-01-24 12:03

    Well the most straightforward thing to do is to just wrap "this.readSuccess" in another function:

    SomeObject.prototype.refreshData = function()
    {
      var obj = this;
      var read_obj = new SomeAjaxCall("read_some_data", { }, 
        function() { obj.readSuccess(); }, function() { obj.readFail(); });
    }
    

    Some Javascript frameworks provide a utility to "bind" a function to an object, which simply means that it creates one of those little functions for you. Note that the variable "obj" will be "remembered" by those little functions, so when your handlers are called the "this" reference will be to the object that was used to call "refreshData".

提交回复
热议问题