Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access an instance variable within a Promise callback?

Let's say I have a basic dumb javascript class :

var FunctionX = function(configs) {
this.funcConfigs = configs;
}

FunctionX.prototype.getData = function() {
  return $.get('/url');
}

FunctionX.prototype.show = function(promise) {
  console.log(this.funcConfigs); // <-- this here is the promise itself, I'm looking to get the instance's configs
}

FunctionX.prototype.setup = function() {
  this.GetData().then(show);
}

var f = new FunctionX({ "a": "b" });
f.setup();

Now I'm trying here in the show function to access the instance variable "funcConfig". "This" is the promise, and "funcConfigs" directly returns undefined.

I tried to resolve this issue with a .resolveWith(this) but it does not solve this issue.

How can I access the instances variables in this scope context?

like image 998
Erick Avatar asked Sep 06 '25 17:09

Erick


1 Answers

In agreement with user2864740, the issue is most likely caused because this is not what you expect it to be when show is invoked as a callback. To make this work properly, you need to capture the proper this in a closure (e.g. var that = this;), and invoke it explicitly.

In other words...

FunctionX.prototype.setup = function() {
   var that = this;

   this.getData().then(function () {
      that.show();
   });
}

EDIT: For a slightly cleaner syntax (using underscore.js):

FunctionX.prototype.setup = function() {
   var that = this;

   this.getData().then(_.bind(this.show, this));
}
like image 161
jeremyalan Avatar answered Sep 08 '25 13:09

jeremyalan