.call() / .apply() with NO parameters VS simply calling a function with () parenthesis

前端 未结 2 999
深忆病人
深忆病人 2020-12-18 05:22

I\'ve seen it done differently in code out there, but is there any benefit or reason to doing a (blank params) .call / .apply over a regular ()

相关标签:
2条回答
  • 2020-12-18 05:55

    When you call a method with func();, this variable inside the method points to window object.

    Where as when you use call(...)/apply(...) the first parameter passed to the method call becomes this inside the method. If you are not passing any arguments/pass null or undefined then this will become global object in non strict mode.

    0 讨论(0)
  • 2020-12-18 06:09

    Yes, there is an important difference in some cases. For example, dealing with callbacks. Let's assume you have a class with constructor that accepts callback parameter and stores it under this.callback. Later, when this callback is invoked via this.callback(), suddenly the foreign code gets the reference to your object via this. It is not always desirable, and it is better/safer to use this.callback.call() in such case.

    That way, the foreign code will get undefined as this and won't try to modify your object by accident. And properly written callback won't be affected by this usage of call() anyways, since they would supply the callback defined as an arrow function or as bound function (via .bind()). In both such cases, the callback will have its own, proper this, unaffected by call(), since arrow and bound functions just ignore the value, set by apply()/call().

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