I have a function:
function func1(callback){
var num = 11111;
callback.call(num);
}
Now i call it:
func1(function(num){
console.log("num= " + num);
});
But i got that num is undefined.
Whats can be wrong?
Function.call() will call the function with the scope of passed reference , you just need to call it not with any particular scope
function func1(callback){
var num = 11111;
callback(num);
}
Or if you want to call in any scope the first parameter is always reference , so pass your params after that, e.g.:
callabck.call(reference, param1, param2);
callback.apply(reference, [param1, param2]);
Because when you use call to call the callback function, the num is being set as the implicit this in the function being called, change to:
callback(num);
Instead of callback.call(num);.
From the MDN Documentation
The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.
callmethod. Why? Just call it like a function:callback(num).