0

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;
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.