[英]Store reference to `call` function
我注意到今天早些时候有些奇怪。 我似乎无法存储对函数的call
属性的引用,然后执行它。 例:
var log = console.log;
log.call(console, 'This works');
var logCall = console.log.call;
logCall(console, 'This does not');
在我看来,这似乎是完全合法的Javascript,但是第二次调用总是给我以下错误: undefined is not a function
。 在这里随意使用它,您将获得相同的结果。
那么,为什么Javascript阻止我以这种方式调用call
?
编辑:在阅读SimpleJ的答案后,我终于明白了。 因此,我将通过如何使以上功能起作用来对此进行更新:
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
收到正确的this
值,但console.log.call
没有得到正确的this
值。 如您所见,我基本上必须执行console.log.call.call
。 显然,您永远不会真正使用这样的代码,我只是很好奇。
您需要保留与控制台的绑定。 尝试这个:
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/
这是我在JavaScript中最喜欢的代码:
var bind = Function.bind;
var call = Function.call;
var bindable = bind.bind(bind);
var callable = bindable(call);
您可以使用bindable
功能,以抢参考f.bind
。 同样,您可以使用callable
函数来获取对f.call
的引用,如下所示:
var log = callable(console.log, console);
现在,您需要做的就是像其他任何函数一样调用log
函数:
log("Hello World!");
那是所有人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.