There's no simple explanation for
this depends on how the function is called. Having read many explanations on
this online, Arnav Aggrawal's explanation was the clearest. The following rules are applied:
- If the
newkeyword is used when calling the function,
thisinside the function is a brand new object.
bindare used to call/create a function,
thisinside the function is the object that is passed in as the argument.
- If a function is called as a method, such as
thisis the object that the function is a property of.
- If a function is invoked as a free function invocation, meaning it was invoked without any of the conditions present above,
thisis the global object. In a browser, it is the
windowobject. If in strict mode (
undefinedinstead of the global object.
- If multiple of the above rules apply, the rule that is higher wins and will set the
- If the function is an ES2015 arrow function, it ignores all the rules above and receives the
thisvalue of its surrounding scope at the time it is created.
For an in-depth explanation, do check out his article on Medium.
Can you give an example of one of the ways that working with this has changed in ES2015?
ES2015 allows you to use arrow functions which uses the enclosing lexical scope. This is usually convenient, but does prevent the caller from controlling context via
.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.