This in Javascript.
Hi everyone 👋. In this article, I will briefly discuss what This in Javascript is?
First, What are methods in Javascript?
Methods are functions that are associated with a specific object. They are functions defined within an objects. To call a method, you use the dot notation (.)
For instance,
let laptop = {
cpu: 'i9',
ram: 16,
brand: 'HP',
greet: function(){
console.log('Hello World');
}
}
laptop.greet();
//Hello World
What is This?
The ‘This’ keyword has numerous functions in Javascript. It mostly determines what object it refers to during any point of code execution. It can be used in different scenarios. For instance,
Let laptop = {
cpu: 'i9',
ram: 16,
brand: 'HP',
getConfig: function (){
console.log(laptop.cpu);
}
}
laptop.getConfig();
//i9
However, when ‘this’ is used inside a function that’s defined as a property (method) of an object, ‘this’ refers to that object itself. Thus, it is able to access the object’s properties and methods.
let laptop = {
cpu: 'i9',
ram: 16,
brand: 'HP',
getConfig: function() {
console.log(this.cpu); // this refers to the laptop object
}
}
laptop.getConfig();
// i9
This = it represents the current object calling the variable or method.
let laptop2 = {
cpu: 'i7',
ram: 16,
brand: 'Apple',
getConfig: function(){
console.log(this.cpu);
}
}
let laptop1 = {
cpu: '19',
ram: 16,
brand: 'HP',
getConfig: function(){
console.log(this.cpu);
}
}
if(laptop1.cpu > laptop2.cpu){
console.log(laptop1);
}
else{
console.log(laptop2);
}
//{cpu: 'i9', ram: 16, brand: 'HP', getConfig: [Function: getConfig] }
The This keyword represents the current object . It is essential for referencing the current object within a function.
let laptop2 = {
cpu: 'i7',
ram: 16,
brand: 'Apple',
getConfig: function(){
console.log(this.cpu);
}
}
let laptop1 = {
cpu: '19',
ram: 16,
brand: 'HP',
compare: function(other){
if(this.cpu > other.cpu)
console.log(this);
else
console.log(other);
},
getConfig: function(){
console.log(this.cpu);
}
}
laptop1.compare(laptop2);
//{cpu: 'i9,
//ram: 16,
//brand: 'HP',
//compare: [Function: compare],
//getConfig: [Function: getConfig] }
Kindly note that these tutorials are for beginners in Javascript and those looking to broaden their knowledge. See you soon.