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

删除回忆录丶 提交于 2019-12-03 18:04:10

问题


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 () function execution.

This of course is an over-simplified example

var func = function () { /* do whatever */ };

func.call();
func.apply();

VERSUS just the simple parenthesis.

func();

Haven't seen any information on this anywhere, I know why call/apply are used when params are passed.


回答1:


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.




回答2:


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().



来源:https://stackoverflow.com/questions/15903782/call-apply-with-no-parameters-vs-simply-calling-a-function-with-paren

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!