Function.prototype.call.call的简写? [英] A shorthand for Function.prototype.call.call?

查看:137
本文介绍了Function.prototype.call.call的简写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个简单的函数:

Consider this simple function:

function my(p) { console.log(p) }

我可以这样称呼它:

my("Hello");

同样如此:

And also like so:

my.call(this, "Hello");

此外,这是可能的:

Moreover, this is possible:

Function.prototype.call.call(my, this, "Hello");






功能方式的简写



我对最后一个选项感兴趣 - 最实用的选项,但由于时间太长,我试图做一个简写:


A shorthand for the functional way

I am interested in the last option - the most functional one, but since it's too long I tried to make a shorthand:

var call = Function.prototype.call.call;

为了像这样打电话给我:

in order to call my like this:

call(my, this, "Hello");

但是我得到这个TypeError:

But I get this TypeError:

TypeError: Function.prototype.call called on incompatible undefined

任何人知道,这里有什么问题?

Anybody knows, what's wrong here?

推荐答案

当您说

var call = Function.prototype.call.call;

上一次调用会丢失其实际上下文。你需要明确地说,调用属于 Function.prototype.call

the last call loses its actual context. You need to explicitly say that the call belongs to Function.prototype.call.

你可以通过创建一个新的函数来实现,像这样绑定它

You can do that, by creating a new function, which actually binds it like this

var call = Function.prototype.call.call.bind(Function.prototype.call);
call(my, this, "Hello");
// Hello

绑定函数返回一个新的函数,当被调用的时候,上下文( this )被设置为 Function.prototype.call

The bind function returns a new function, which when invoked will have the context (this) set as Function.prototype.call.

这篇关于Function.prototype.call.call的简写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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