Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

javascript - Store reference to `call` function

I noticed something curious earlier today. I can't seem to store a reference to the call property of a function, then execute it. Example:

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

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

To me, this seems like perfectly legal Javascript, but the second invocation always gives me the error that undefined is not a function. Feel free to play around with it here, you'll get the same results.

So why does Javascript prevent me from calling call in this manner?

EDIT: I finally got it straight in my head after reading SimpleJ's answer. 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 was receiving the proper this value, but console.log.call wasn't given a proper this value. So as you can see, I basically had to execute console.log.call.call. Obviously you'd never really use code like this, I was just curious.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to keep the binding to console. Try this:

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

or

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

For a bound reference to log.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...