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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…