Saturday, July 22, 2017

Simple Example of JavaScript *this* Referring to Two Different Objects

Let's say we have this JavaScript object:



What will this display in the console log?

That depends on how displayThis() is called.


If we called it this way:


musician.displayThis();


this would be the musician object:




Why? Because we called displayThis() via the musician object, and the musician object's this is itself.


If we called it this way:


var outside = musician.displayThis;
outside();

this would be the Window object:


Why? Because we called displayThis() via the outside object, and the outside object's this is Window.

1 comment:

Lily said...

Thank you for ssharing this