Professional Documents
Culture Documents
Ritik
14
JavaScript + FOLLOW
location
Ritik Apr 18 ・2 min read
India
Most of the time we confuse with this keyword in JavaScript. So lets simplify
it. dev.to is where software developers stay in
the loop and avoid career stagnation.
"this" is just used to create a reference to any object.
Sign up (it's free!)
Let say we have a two object "studentFirst" and "studentSecond".
const studentFirst = {
name:"ritik",
age:"21"
}
const studentSecond = {
name:"gaurav",
age:"45"
}
And a function "getDetails" which will log the student details in console.
function getDetailsFirst(){
console.log(`${studentFirst.name} is ${studentFirst.age} years old.`);
}
function getDetailsSecond(){
console.log(`${studentSecond.name} is ${studentSecond.age} years old.`);
}
getDetailsFirst();
getDetailsSecond();
Above we are using two seperate function and using object properties by
calling their Object seperatly.
It can be done more efficiantly using "this". Lets see:
const studentFirst = {
name:"ritik",
age:"21"
}
const studentSecond = {
name:"gaurav",
age:"45"
}
function getDetails(){
console.log(`${this.name} is ${this.age} years old.`);
}
console.log(this);
//Window {parent: Window, opener: null, top: Window, length: 4, frames: Window, …}
const student = {
name:"ritik",
getDetails(){
console.log(this);
}
}
student.getDetails();
//{name: "ritik", getDetails: ƒ}
const student = {
name:"ritik",
getDetails(){
console.log(this.name);
}
}
student.getDetails();
//ritik
const student = {
name:"ritik",
getDetails(){
console.log(student.name);
}
}
student.getDetails();
//ritik
Most of the time "this" is seen inside a constructor which is one of the
usecase of it.
Ritik + FOLLOW
PREVIEW SUBMIT
Apr 18
***
tl;dr this refers to the thing on the left side of the dot
2 REPLY
48 86
135 9 + FOLLOW
98 6