存储对`call`函数的引用 [英] Store reference to `call` function

查看:68
本文介绍了存储对`call`函数的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天早些时候注意到了一些奇怪的事情。我似乎无法存储对函数的调用属性的引用,然后执行它。示例:

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');

对我来说,这似乎是完全合法的Javascript,但第二次调用总是给我错误 undefined不是函数。随意使用它来这里,你会得到相同的结果。

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.

那么为什么Javascript会阻止我以这种方式调用调用

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

编辑:在阅读SimpleJ的回答后,我终于明白了。因此,我将更新以了解如何使上述工作:

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');

问题是 console.log 是收到正确的值,但 console.log.call 未获得正确的这个值。所以你可以看到,我基本上必须执行 console.log.call.call 。显然你从来没有真正使用这样的代码,我只是很好奇。

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.

推荐答案

你需要保持绑定到控制台。试试这个:

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

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

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

对于 log 的绑定引用。

编辑:
jsfiddle: http:// jsfiddle.net/67mfQ/2/

这篇关于存储对`call`函数的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆