this
this
Refers to the current context
Its value depends on how the function is called
How does it work?
The following rules are applied:
If the
newkeyword is used when calling the function,thisinside the function is a brand new object.If
apply,call, orbindare 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
obj.method()—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 thewindowobject. If in strict mode ('use strict'),thiswill beundefinedinstead of the global object.If multiple of the above rules apply, the rule that is higher wins and will set the
thisvalue.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.
References
Examples
What is the result of the following code?
var fullname = 'John Doe';
var obj = {
fullname: 'Colin Ihrig',
prop: {
fullname: 'Aurelio De Rosa',
getFullname: function() {
return this.fullname;
}
}
};
console.log(obj.prop.getFullname());
var test = obj.prop.getFullname;
console.log(test());Answer:
Aurelio De Rosa
John DoeIn console.log(obj.prop.getFullname()); getFullname() is invoked as a function of the obj.prop object. So, the context refers to the latter and the function returns the fullname property of this object.
In var test = obj.prop.getFullname;the context refers to the global object (window). This happens because test is implicitly set as a property of the global object. For this reason, the function returns the value of a property called fullname of window, which in this case is the one the code set in the first line of the snippet.
Last updated