The JavaScript bind(this) method is very confusing for beginners. But It is being used frequently when we have deep nested context. The Problem with the code below is that when a promise is fulfilled reference to 'this' will no longer be available.
promise.then(function(data) {this.foo(data, "data");
}, function(err) {
// error handling
});
One of the common solutions is to create a variable 'self' and below code will work.
var self = this;promise.then(function(data) {
self.foo(data, "data");
}, function(err) {
// error handling
});
Personally, I don't like the above approach. We can have better and cleaner code using bind() to keep the context of "this".promise.then(
function( data ) {this.foo( data, "data" );
}.bind(this),
function(err) {
this.error(err);
}.bind(this)
);
Comments
Post a Comment