panthro
panthro

Reputation: 24069

Promises and accessing this

I have two functions:

p.test = 'test';

p.functionA = function(){

    console.log('function A');
    var dfd = new $.Deferred();

    setInterval(function(){dfd.resolve();}, 2000);

    return dfd.promise();

};


p.functionB = function(){

    console.log('function B');
    console.log(this.test);
    var dfd = new $.Deferred();

    setInterval(function(){dfd.resolve();}, 2000);

    return dfd.promise();
};

The functions are called like so:

this.functionA().then(this.functionB);

I wish to get the value of test in function B yet it is undefined. Why? How can I access it?

Upvotes: 0

Views: 52

Answers (2)

Paul
Paul

Reputation: 141887

You can bind the context to the function:

this.functionA().then( this.functionB.bind( this ) );

If you want to support IE8 and don't want to use the bind polyfill, you can also use jQuery's proxy:

this.functionA().then( $.proxy( this.functionB, this ) );

If you don't want to keep repeating this, you could also use a more complete Promise library, like Bluebird. You would need to update your return values to return a trusted promise:

return Promise.resolve( dfd.promise() ).

Then you could use:

Promise.bind(this).then( this.functionA ).then( this.functionB ). ...

Upvotes: 3

guest271314
guest271314

Reputation: 1

Try utilizing deferred.resolveWith()

var p = {};

p.test = 'test';

p.functionA = function() {

  console.log('function A');
  var dfd = new $.Deferred();

  setTimeout(function() {
    // set context : `this` of returned jQuery promise to `p`
    dfd.resolveWith(p);
  }, 2000);

  return dfd.promise();

};


p.functionB = function() {
  // `this`: `p`
  console.log('function B');
  console.log(this.test);
  var dfd = new $.Deferred();

  setTimeout(function() {
    dfd.resolve();
  }, 2000);

  return dfd.promise();
};

p.functionA().then(p.functionB);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

Upvotes: 0

Related Questions