Are you looking for the keyword β€œthis”? πŸ™„

Jainam Desai
Mozilla Firefox Club VIT Vellore
2 min readDec 17, 2020
Photo by Irvan Smith on Unsplash

What is this πŸ˜₯

In JavaScript this refers to the current object that is executing the current function. It has different values depending on where it is used.

Read more or about objects here.

The this reference 😳

βœ… If the function is inside an Object then this refers to the that object.

Example:

const cookie = {
flavour: "chocolate",
eat() {
console.log(`I am a ${this.flavour} πŸͺ and I was eaten!`);
},
};
Cookie.eat();// This is another way of writing the above code.
const cookie = {
flavour: "chocolate",
eat: function () {
console.log(`I am a ${this.flavour} πŸͺ and I was eaten!`);
},
};
// Both the codes are same.

This will not work if we use it inside an Arrow Function or inside a nested function.

Example:

// this will not work
const cookie = {
flavour: "chocolate",
eat: () => {
console.log(`I am a ${this.flavour} πŸͺ and I was eaten!`);
},
};
// ORconst cookie = {
flavours: ["chocolate", "stawberry", "vanilla"],
eatAllCookies() {
this.flavours.forEach(function (flavour) {
// πŸ‘ˆ Anonymous nest function
console.log(`I am ${flavour} πŸͺ and I was eaten!`); // πŸ‘ˆ Will output "I am 'undefined' and I was eaten!"
});
},
};

To bind the object we need to pass the this object as an argument to the forEach() function.

const cookie = {
flavours: ["chocolate", "stawberry", "vanilla"],
eatAllCookies() {
this.flavours.forEach(function (flavour) {
console.log(`I am ${flavour} πŸͺ and I was eaten!`);
}, this); // πŸ‘ˆ here this refers to the current "flavours" array, which in turn is an object.
},
};
// Works like a charm πŸ˜‹
cookie.eatAllCookies();

βœ… If the function is a regular function then this refers to the window object in browser and the global object in node.

Example:

function eatCookie() {
console.log(this);
console.log("this doesn't have a πŸͺ object");
}
// It will print the window object if run in browser and global if run in node.

We can prevent this from binding to the global if we use strict mode.

this is undefined in a normal function when using the strict mode.

"use strict";function eatCookie() {
console.log(this);
console.log("this doesn't have anything!");
}
// the above code will not log the global or window object, instead it will print 'undefined'.

this again behaves different if we invoke a function using the new operator.

function Cookie() {
this.flavour = "I am a chocolate πŸͺ";
console.log(this.flavour, "and I was eaten!");
}
const cookie = new Cookie();

When we use the new operator, it creates a new empty object { }. Then names that object Cookie and adds flavour property to it.

--

--