Save link to `call` function

Today I noticed something curious. It seems I can’t save the reference to the call property of the function and then execute it. Example:

 var log = console.log; log.call(console, 'This works'); var logCall = console.log.call; logCall(console, 'This does not'); 

For me, this seems like perfectly legal Javascript, but the second call always gives me an error that is undefined is not a function . Feel free to play with him here , you will get the same results.

So why does Javascript stop me from calling call this way?

EDIT: I finally figured it out right in my head after reading SimpleJ. So I'm going to update this with how you can get the above to work:

 var log = console.log; log.call(console, 'This works'); var logCall = console.log.call; logCall.call(console.log, console, 'This works now too'); 

The problem was that console.log getting the correct this value, but console.log.call not assigned the correct this value. So, as you can see, I basically had to execute console.log.call.call . Obviously, you would never use such code, I was just curious.

+1
javascript
source share
2 answers

You need to save the binding to the console. Try the following:

 var logCall = console.log.call.bind(console.log); // example: logCall(console, "foobar"); 

or

 var log = console.log.bind(console); // example: log("foobar"); 

For a link to log .

Edit: jsfiddle: http://jsfiddle.net/67mfQ/2/

+3
source share

This is my favorite JavaScript code:

 var bind = Function.bind; var call = Function.call; var bindable = bind.bind(bind); var callable = bindable(call); 

You can use the bindable function to get a link to f.bind . Similarly, you can use the callable function to get a link to f.call as follows:

 var log = callable(console.log, console); 

Now all you have to do is call the log function, like any other function:

 log("Hello World!"); 

What are all people.

+2
source share

All Articles