Reputation: 565
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?
Upvotes: 0
Views: 318
Reputation: 2672
To put it simply, you don't have to. Unless you want your callback function to have its context be the "App" object. For example:
// Regular callback:
var App = {
method : function (value, callback) {
if (typeof callback === 'function') {
callback();
}
}
}
App.method('Hey there', function(){
console.log(
'A regular callback was executed!',
'And its context is Window:',
this === window
);
});
// Context modified callback:
var App = {
method : function (value, callback) {
if (typeof callback === 'function') {
callback.call( this );
}
}
}
App.method('Hey there', function(){
console.log(
'A context modified callback was executed!',
'And its context is App:',
this === App
);
});
I hope that helps!
Upvotes: 1
Reputation: 413915
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.
Upvotes: 0