[英]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. 我似乎无法存储对函数的
call
属性的引用,然后执行它。 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
. 在我看来,这似乎是完全合法的Javascript,但是第二次调用总是给我以下错误:
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? 那么,为什么Javascript阻止我以这种方式调用
call
?
EDIT: I finally got it straight in my head after reading SimpleJ's answer. 编辑:在阅读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
was receiving the proper this
value, but console.log.call
wasn't given a proper this
value. 问题是
console.log
收到正确的this
值,但console.log.call
没有得到正确的this
值。 So as you can see, I basically had to execute console.log.call.call
. 如您所见,我基本上必须执行
console.log.call.call
。 Obviously you'd never really use code like this, I was just curious. 显然,您永远不会真正使用这样的代码,我只是很好奇。
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
. 有关
log
的绑定参考。
Edit: jsfiddle: http://jsfiddle.net/67mfQ/2/ 编辑:jsfiddle: http : //jsfiddle.net/67mfQ/2/
This is my favorite code in JavaScript: 这是我在JavaScript中最喜欢的代码:
var bind = Function.bind;
var call = Function.call;
var bindable = bind.bind(bind);
var callable = bindable(call);
You can use the bindable
function to grab a reference to f.bind
. 您可以使用
bindable
功能,以抢参考f.bind
。 Similarly you can use the callable
function to grab a reference to f.call
as follows: 同样,您可以使用
callable
函数来获取对f.call
的引用,如下所示:
var log = callable(console.log, console);
Now all you need to do is call the log
function like any other function: 现在,您需要做的就是像其他任何函数一样调用
log
函数:
log("Hello World!");
That's all folks. 那是所有人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.