Blog

this

JS

this keyword

Brief on this keyword

Ragav Kumar V

Ragav Kumar V

Aug 20, 2022 ยท 1 min read

  1. this requires context (book)
  2. this is a reference word
  3. until the function is called this does not point to anything

Key name & value name must be same


_11
const student = {
_11
firstName: "Vishy",
_11
lastName: "Anand",
_11
fullName: function () {
_11
return `${this.lastName}, ${this.firstName}`;
_11
},
_11
};
_11
_11
console.log(student.fullName());
_11
_11
// until the function is called `this` does not point to anything

student. -> this


_7
const student2 = {
_7
firstName: "Nihal",
_7
lastName: "Sarin",
_7
fullName: student.fullName,
_7
};
_7
_7
console.log(student2.fullName());

  1. call - passing arguments by comma separated
  2. apply - passing arguments as an array
  3. bind - always returns a new function

_17
const student4 = {
_17
firstName: "Gukesh",
_17
lastName: "Dommaraju",
_17
};
_17
_17
const intro = function (state, country) {
_17
return `${this.lastName}, ${this.firstName} is from ${state}, ${country}!!!`;
_17
};
_17
_17
console.log(intro.call(student4, "TN", "India"));
_17
// Dommaraju, Gukesh is from TN, Indian!!!
_17
console.log(intro.apply(student4, ["TN", "India"]));
_17
// Dommaraju, Gukesh is from TN, India!!!
_17
_17
const gukeshIntro = intro.bind(student4);
_17
console.log(gukeshIntro("TN", "India"));
_17
// Dommaraju, Gukesh is from TN, India!!!

@ragavkumarv
swipe to next โžก๏ธ