Sitemap

JavaScript This

2 min readDec 30, 2018

--

The JavaScript “this” keyword refers to the object it belongs to, which can have a different value depending on where it is used.

https://www.zeolearn.com/magazine/understanding-the-this-keyword-in-javascript

Understanding what “this” is in JavaScript and learning how to determine its value throughout your code is as easy as following four simple rules. The rules should be reviewed in order and if multiple rules happen to apply, the highest rule takes precedence.

Rules of This

  1. If the “new” keyword is used when calling the function, “this” inside the function is a brand new object.
Press enter or click to view image in full size

Get Brad Newman’s stories in your inbox

Join Medium for free to get updates from this writer.

2. If “apply”, “call”, or “bind” are used to call a function, “this” inside the function is the object that is passed in as the argument.

Press enter or click to view image in full size

3. If a function is called as a method — meaning dot notation is used to invoke the function — “this” is the object to which the function belongs. In other words, when a dot is to the left of a function invocation, “this” is the object to the left of the dot.

Press enter or click to view image in full size

4. If a function is invoked as a free function invocation, meaning it was invoked without any of the conditions present above, “this” is the global object. In a browser, it’s the “window”.

Press enter or click to view image in full size

Some libraries will automatically bind the value of “this” to the most useful object. If “this” seems to be an unexpected value, check the documentation for the library.

--

--

Brad Newman
Brad Newman

Written by Brad Newman

Full Stack Web Developer | Software Engineer