在JavaScript中使用Function.call.apply的目的是什么? [英] What's the purpose of using Function.call.apply in JavaScript?

查看:129
本文介绍了在JavaScript中使用Function.call.apply的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我偶然发现用于创建的Function.call.apply hack时,我浏览了 JavaScript Garden 快速,无约束的包装纸。它说:

I was browsing through the JavaScript Garden when I stumbled upon the Function.call.apply hack which is used to create "fast, unbound wrappers". It says:


另一个技巧是同时使用call和apply来创建快速,未绑定的包装器。

Another trick is to use both call and apply together to create fast, unbound wrappers.

function Foo() {}

Foo.prototype.method = function(a, b, c) {
    console.log(this, a, b, c);
};

// Create an unbound version of "method" 
// It takes the parameters: this, arg1, arg2...argN
Foo.method = function() {

    // Result: Foo.prototype.method.call(this, arg1, arg2... argN)
    Function.call.apply(Foo.prototype.method, arguments);
};


我不明白为什么还要使用Function.call .apply当Function.apply就足够了。毕竟,它们在语义上是等价的。

What I don't understand is why bother using Function.call.apply when Function.apply would suffice. After all, both of them are semantically equivalent.

推荐答案

不, Function.call.apply Function.apply 不一样。

让我们说原来的来电者调用

Let's say the original caller invokes

Foo.method(t, x, y, z)

通过调用和一起应用,就像在JavaScript Garden代码中一样。执行

With call and apply together, as in the JavaScript Garden code. This executes

Function.call.apply(Foo.prototype.method, arguments);

这是(松散地,写参数 in array-notation):

which is (loosely, writing arguments in array-notation):

Function.call.apply(Foo.prototype.method, [t, x, y, z]);

使用<$调用 Function.call c $ c> this == Foo.prototype.method

which invokes Function.call with this==Foo.prototype.method:

Foo.prototype.method.call(t, x, y, z)

调用 Foo.prototype .method 设置为 t 和参数 x y z 。甜。就像在评论中一样。我们已经成功制作了一个包装器。

which calls Foo.prototype.method with this set to t and arguments x, y, and z. Sweet. Just like in the comments. We have successfully made a wrapper.

现在假设你离开说只是 Function.apply 而不是 Function.call.apply ,您声称它在语义上是等效的。你会有

Now suppose you left said just Function.apply instead of Function.call.apply, which you claim is semantically equivalent. You would have

Function.apply(Foo.prototype.method, arguments);

这是(宽松地)

Function.apply(Foo.prototype.method, [t, x, y, z]);

调用函数函数(唉! )设置为 Foo.prototype.method 和参数 t x y z

which calls the function Function (ugh!) with this set to Foo.prototype.method and arguments t, x, y, and z.

完全不一样。

这篇关于在JavaScript中使用Function.call.apply的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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