this
keyword
this
requires context (book)this
is a reference word- until the function is called
this
does not point to anything
Key name & value name must be same
_11const student = {_11 firstName: "Vishy",_11 lastName: "Anand",_11 fullName: function () {_11 return `${this.lastName}, ${this.firstName}`;_11 },_11};_11_11console.log(student.fullName());_11_11// until the function is called `this` does not point to anything
student.
-> this
_7const student2 = {_7 firstName: "Nihal",_7 lastName: "Sarin",_7 fullName: student.fullName,_7};_7_7console.log(student2.fullName());
Manually providing (explicit) context
- call - passing arguments by comma separated
- apply - passing arguments as an array
- bind - always returns a new function
_17const student4 = {_17 firstName: "Gukesh",_17 lastName: "Dommaraju",_17};_17_17const intro = function (state, country) {_17 return `${this.lastName}, ${this.firstName} is from ${state}, ${country}!!!`;_17};_17_17console.log(intro.call(student4, "TN", "India"));_17// Dommaraju, Gukesh is from TN, Indian!!!_17console.log(intro.apply(student4, ["TN", "India"]));_17// Dommaraju, Gukesh is from TN, India!!!_17_17const gukeshIntro = intro.bind(student4);_17console.log(gukeshIntro("TN", "India"));_17// Dommaraju, Gukesh is from TN, India!!!
@ragavkumarv
swipe to next โก๏ธ