Stefan Stefan - 6 months ago 29
Javascript Question

bind() on promise error function - javascript

I found this codesnippet. Can somebody explain the purpose of the

.bind(this)
in this context? Where would we be able to access
this
now? In the resolved promise?

get: function(endpoint, params, callback) {
var cb = callback || angular.noop;
var deferred = $q.defer();

$http.get(
endpoint,
params
).
success(function(data) {
deferred.resolve(data);
return cb();
}).
error(function(err) {
deferred.reject(err);
return cb(err);
}.bind(this));

return deferred.promise;
}

Answer

The purpose of the bind(newContext) method of the function object is to return a new function with the context this as the first parameter passed to bind().

For example:

var message = {text: 'I am the context'};

function tryMe() {
  console.log(this);
}

tryMe(); // will print undefined (in strict mode) or global object
tryMe.bind(message)(); // will print '{text: 'I am the context'}'

In your example, the idea of using bind() is to keep the context this of the get() method in the error handler:

.error(function(err) {
    deferred.reject(err);
    //now use this.get() for example
    return cb(err);
  }.bind(this));

However no methods associate with the new context were called in the handler.

See more details in Gentle explanation of this.

Comments