Stefan Stefan - 11 months ago 60
Javascript Question

bind() on promise error function - javascript

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

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

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

success(function(data) {
return cb();
error(function(err) {
return cb(err);

return deferred.promise;


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() {

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) {
    //now use this.get() for example
    return cb(err);

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

See more details in Gentle explanation of this.