What's the purpose of using Function.call.apply in JavaScript?

后端 未结 2 1287
予麋鹿
予麋鹿 2020-12-02 21:38

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:

相关标签:
2条回答
  • 2020-12-02 21:59

    It means you can use the methods from an object on another one.

    A good example is the arguments variable all functions have, it's like an array but not an array so you can call array's methods on it thus:

    Array.prototype.join.call(arguments, ",");
    
    0 讨论(0)
  • 2020-12-02 22:08

    No, Function.call.apply and Function.apply are not the same in this case.

    Let's say the original caller invokes

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

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

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

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

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

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

    Foo.prototype.method.call(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.

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

    which is (loosely)

    Function.apply(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.

    Not the same at all.

    0 讨论(0)
提交回复
热议问题