What is this in JavaScript

this represents the object calling the script.

Take for example:
var x = 35;

var places x here, right within this context.

And what is this context? This is the global context.
And what is the global context? it is the object window environment.

So now we can call back x in the console:
and the output is 35, right?

We could also do it this way:


and the output is 35.

So x; is actually a shortcut for window.x;

But the question is: What is this?

this is a placeholder. It is meant to be generic. It will be replaced by the object that owns the environment.

Who owns the current environment? window

So instead of window.x;
We could code it this.x;

And why would we do such thing?

Because once we create a script using this instead of the object name itself, it becomes portable.

by coding this.x; we can take this script anywhere and it will always work under that specific environment where it is being applied.

Easier said than done! There are some issue but they are beyond this explanation.

You can read more about those issues on my latest book.

If you love JavaScript like I do, you will enjoy reading it.
Use the free amazon “Kindle for PC” app to read it on your computer.


Author: tarau

technical writer, web technologies

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s