A function's this
argument is usually set implicitly, depending on how the function is called. Ordinary function calls, method calls, and constructor calls all lead to a different this
value.
We can also call a function with an explicit this
argument using Function.prototype.call()
or Function.prototype.apply()
. Both methods accept a thisArg
as their first parameter and a variable number of additional arguments.
This lesson shows how to use call()
and apply()
and explains how they differ.
Great video, but I have a question. At the last part of the video, you said about a gotcha about using apply
or call
without strict mode, but, isn't it an issue for everything, not only apply
and call
?
Since the usage of strict mode makes it been undefined, and the opposite makes it global.
@Klaus: You're right, outside of strict mode, this
is set to the global object when you make a plain function call like func()
.
The gotcha I was referring to is that if you pass null
or undefined
to call()
or apply()
outside of strict mode, these values will be ignored and the global object will be used as well. If you explicitly use call()
or apply()
in the first place, this is most likely not what you intended.
@Marius: Oh. Got that now!