You can look at it from top to bottom scope:
Alone(global environment) and in a function that isn't called by an object, this
always refers to the global object: window
.
if in an function that is called by an object, this
refers to to that object that called it. At example:
const myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
myObject.fullName(); // Will return "John Doe"
This also applies for a constructor function when being called with the new
keyword(for instantiating objects in case you don't know yet), the difference is that it currently does not hold any value, because it will become a new object and this
then holds the new object.
There are also a few exceptions to these to basic rules:
In an arrow function(ES6) the above object binding rules do not apply, in fact there is no binding at all directly inside it, and this
is always the (inbuilt) object that defined the arrow function, that is, the window
object.
Furthermore, when using 'strict mode', this
is undefined
within a function instead of the window
object.
At last, There are the call()
, apply()
and bind()
methods, is used to refer this to any object. Methods used for manipulating the this
value in situations a developer wants to change and fixate the this
value.
At example:
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
const person2 = {
firstName:"Mary",
lastName: "Doe"
}
// This will return "John Doe":
person.fullName.call(person1);
or 'borrow' a method from another object:
const person = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
const member = {
firstName:"Hege",
lastName: "Nilsen",
}
let fullName = person.fullName.bind(member);
The last two examples are maybe a bit tricky.
sources:
function invocation call() apply() bind()
But that's it actually.