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?
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With