The this
has different values depending on it's lexical environment (physical position in the source code).
This article will focus on the various values of this
at various points in our code.
At the Global Execution Context
At the global execution context stage this
points to the global object, which is the window object on the browser.
console.log(this); // points to the global object.
In a Regular Function Call
Whenever a function is invoked/called, an Execution Context is created, alongside the this
variable, this
in the context of a function call references the global object still.
function randomFunction(){
console.log(this); //points to the global object
);
randomFunction();
Object Method Call
When a function is contained in an object, it is referred to as a method. Whenever a method is called, this
references the object that called that method.
Let's see an example:
let myself = {
name: "Victory",
sayName: function (){
console.log(`my name is ${this.name}`);
},
};
myself.sayName(); //outputs my name is Victory
}
Function inside a method and Arrow Function
Whenever a function inside a method is called, it's this
references the global object.
Some think of this as a bug in JavaScript, I'd like to know your thoughts on this, try it out and comment.
Arrow functions on the other hand behave differently, their this
references the object that contains them.
Let's look at a more robust example.
let legend = {
name: "Cristiano",
status: function (){
console.log(`${this.name} is the greatest of all time`);
let arrowFunction = ()=>{
console.log(this);
};
arrowFunction ();// outputs Cristiano is the greatest of all time
function innerFunction(){
console.log(this); //references the global object
}
innerFunction ();
},
};
legend.status();
Method Borrowing
Say we have two objects, object 1 has a method and object2 borrows that method, when this borrowed method is invoked by object 2, this
references object2 - the object that called the method.
This is pretty straight forward but, let's look at an example.
//Object1
const man ={
gender: "male",
specie: "human",
stateSpecie: function (){
console.log(`I am a ${this.gender} ${this.specie}`);
}
};
man.stateSpecie();// outputs I am a male human
//Object2
const woman = {
gender: "female",
specie: "human"
};
woman.stateSpecie = man.stateSpecie; //method borrowing
woman.stateSpecie(); //outputs I am a female human.
So guys, I hope you've been able to understand the this
keyword, spend more time with the examples till you grasp them totally, try reading the official documentation on it.
My name is Victory, if you have any questions hit me up on Twitter twitter.com/n__victory