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.
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 underthis.callback
. Later, when this callback is invoked viathis.callback()
, suddenly the foreign code gets the reference to your object viathis
. It is not always desirable, and it is better/safer to usethis.callback.call()
in such case.That way, the foreign code will get
undefined
asthis
and won't try to modify your object by accident. And properly written callback won't be affected by this usage ofcall()
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 bycall()
, since arrow and bound functions just ignore the value, set byapply()/call()
.When you call a method with
func();
,this
variable inside the method points towindow
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 thenthis
will become global object in non strict mode.