0

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?

2
  • First argument to call() is a "this" object. Try calling it callback.call(this, num). Commented Nov 24, 2013 at 12:35
  • 1
    You have used the call method. Why? Just call it like a function: callback(num). Commented Nov 24, 2013 at 12:38

2 Answers 2

1

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]);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

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.