JavaScript This
The JavaScript “this” keyword refers to the object it belongs to, which can have a different value depending on where it is used.
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
- If the “new” keyword is used when calling the function, “this” inside the function is a brand new object.
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.
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.
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”.
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.








