I’m reading Javascript Web Applications, from O’Reilly. At various points in the book, the author uses something along the following:
instance.init.apply(instance, arguments);
Does this make any sense? Isn’t this exactly the same as:
instance.init(arguments);
.call() and .apply() are used to manually set the execution context of a function. Why should I use them when I’m intending to use the original execution context anyway?
The point is that
argumentsis an array-like object. Doing …… passes one argument, which is an array-like object containing certain arguments. On the other hand, doing …
… will pass the array-like object as separate arguments. It is true that setting
instanceis kind of useless because you already wrote it, but if using.applyyou simply need to set thethisvalue as well.A quick example of the difference: