There's no simple explanation for this; it is one of the most confusing concepts in JavaScript. A hand-wavey explanation is that the value of this depends on how the function is called. I have read many explanations on this online, and I found Arnav Aggrawal's explanation to be the clearest. The following rules are applied:
new keyword is used when calling the function, this inside the function is a brand new object.apply, call, or bind are used to call/create a function, this inside the function is the object that is passed in as the argument.obj.method() — this is the object that the function is a property of.this is the global object. In a browser, it is the window object. If in strict mode ('use strict'), this will be undefined instead of the global object.this value.this value of its surrounding scope at the time it is created.For an in-depth explanation, do check out his article on Medium.
ES6 allows you to use arrow functions which use the enclosing lexical scope. This is usually convenient, but does prevent the caller from controlling context via .call or .apply—the consequences being that a library such as jQuery will not properly bind this in your event handler functions. Thus, it's important to keep this in mind when refactoring large legacy applications.
Adapted from the Front End Interview Handbook by Yangshun Tay and contributors (MIT License). Source
Spotted a mistake or a rights concern? Report an issue