Asynchronous JavaScript and Object Persistence

I have a JS code something like this:

function myObject()
{
    this.a = 13;

    this.fetchData = function()
    {
        alert(this.a);
        getData(this.processData);
    }

    this.processData = function(data)
    {
        // do stuff with data
        alert(this.a);
    }

    this.fetchData();
}

function getData(callback)
{
    // do async request for data and call callback with the result
}

My problem: the fetchData function has access to my variable through this keyword, but the other processData function is not called when getData is called. I understand why this is happening, but I don’t know how to get around this.

How do you feel about this problem, preferably in the style of OOP? (The getData function must be available for several classes)

+3
source share
2 answers

Two options:

1) Accept getDatathe context parameter (usually called contextor thisArg) and use callback.apply(context, ...)or callback.call(context, ...)to call it. So:

function getData(callback, context) {
    // ...when it time to call it:
    callback.call(context, arg1, arg2);
    // or
    callback.apply(context, [arg1, arg2]);
}

2) , this, . ( "".)

, :

this.fetchData = function()
{
    var self = this;

    alert(this.a);
    getData(getDataCallback);

    function getDataCallback(arg1, arg2) {
        self.processData(arg1, arg2);
    }
}

bind ( , , ). . bind.

: this

+4

, "a" , fetchData, getData, :

function myObject() {
   var a = 13;

   this.fetchData = function() {
      alert(a);
      getData(this.processData);
   }

   this.processData = function(data) {
      // do stuff with data
      alert(a);
   }

   this.fetchData();
}

,

function myObject() {
   this.a = 13;
   var that = this;

   this.fetchData = function() {
      alert(that.a);
      getData(this.processData);
   }

   this.processData = function(data) {
      // do stuff with data
      alert(that.a);
   }

   this.fetchData();
}
+1

Source: https://habr.com/ru/post/1791953/


All Articles