Alicia Brandon Alicia Brandon - 5 months ago 16
Javascript Question

Object literal pattern callback and this confusion

var App = {
method : function (value, callback) {
console.log(value);
if (typeof callback === 'function') {
//here
callback.call( this );
}
}
}

App.method('Hey there', function(){
console.log('callback was executed!');
});


Why do I can't do callback(), but have to call(this) for the callback?

Answer

In the specific case of the callback function you're supplying, it would not matter if you invoked the callback simply with:

   callback();

Your callback code does not refer to this at all, so it makes no difference what value it has.

If, however, the callback wanted to refer to other parts of the App object, then invoking with callback.call(this) would ensure that this refers to App in the callback. Example:

var App = {
  method : function (value, callback) {
    console.log(value);  
    if (typeof callback === 'function') {
      //here
      callback.call( this );
    } 
  },
  property: "HELLO WORLD"
} 

App.method('Hey there', function(){
  console.log('callback was executed! Property value is: ' + this.property);
}); 

With that code, this would have to refer to App in order for the console.log() call to access the object property. The use of .call() ensures that.

Comments