Function.prototype.call.call的简写?

Ant*_*ald 3 javascript functional-programming function

调用函数的方法

考虑这个简单的功能:

function my(p) { console.log(p) }
Run Code Online (Sandbox Code Playgroud)

我可以这样称呼它:

my("Hello");
Run Code Online (Sandbox Code Playgroud)

也像这样:

my.call(this, "Hello");
Run Code Online (Sandbox Code Playgroud)

此外,这是可能的:

Function.prototype.call.call(my, this, "Hello");
Run Code Online (Sandbox Code Playgroud)

功能方式的简写

我对最后一个选项很感兴趣 - 最实用的选项,但是因为它太长了我试图做一个简写:

var call = Function.prototype.call.call;
Run Code Online (Sandbox Code Playgroud)

为了打电话给我这样:

call(my, this, "Hello");
Run Code Online (Sandbox Code Playgroud)

但是我得到了这个TypeError:

TypeError: Function.prototype.call called on incompatible undefined
Run Code Online (Sandbox Code Playgroud)

谁知道,这里有什么问题?

the*_*eye 8

当你说

var call = Function.prototype.call.call;
Run Code Online (Sandbox Code Playgroud)

最后一个call失去了它的实际背景.你需要明确地说call属于Function.prototype.call.

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

var call = Function.prototype.call.call.bind(Function.prototype.call);
call(my, this, "Hello");
// Hello
Run Code Online (Sandbox Code Playgroud)

bind函数返回一个新函数,该函数在调用时将context(this)设置为Function.prototype.call.