If you do foo.call(test)
, then inside of foo()
, this
will be test
.
But, inside of foo()
, when you then call bar()
, the this
value will then be reset inside of bar()
to its default value.
EVERY function call in Javascript sets a new value of this
according to how the function is called.
A plain function call such as bar()
, sets the value of this
to the global object if not running in strict mode or to undefined
if running strict mode.
To review, the methods for setting the this
value to something specific are:
foo.call(test, ...); // sets this to test
foo.apply(test, ...); // sets this to test
obj.method(); // sets this to obj
var x = foo.bind(test);
x(); // sets this to test
var x = new foo(); // create a new object and sets this to the new object
foo(); // this set to global object or undefined (in strict mode)
Just remember that the value of this
is reset on every function call in Javascript according to the above rules. It is never "inherited" from the previous value. It is always set to something new on every function call based on how the function call was made. This is a common misunderstanding for people new to Javascript (I was tripped up by the same thing many moons ago).
It is also worth noting that a callback function may have the value of this
set to something specific (using .apply()
or .call()
internally) when the callback function is called. For example:
function submitHandler(e) {
// value of this is in this function is set
// by addEventListener to the DOM object that handled the event
}
document.getElementById("submit").addEventListener("click", submitHandler);
Other references on the topic:
When you pass 'this' as an argument
A Better Understanding of This
How does the "this" keyword work?