.call() / .apply() with NO parameters VS simply ca

2019-01-25 14:15发布

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.

2条回答
闹够了就滚
2楼-- · 2019-01-25 14:54

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

查看更多
神经病院院长
3楼-- · 2019-01-25 15:03

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.

查看更多
登录 后发表回答