this” keyword in JS — Part 1 (In case of Objects)

Gurinderpal Singh Narang

--

In JavaScript, this keyword refers to an object, which object depends on how this is being invoked(used or called). this keyword refers to different objects depending on how it is used:

  1. In an object method, this refers to the object. Here is an example:
const profile = {
name: "Harry",
getName: function() {
return this.name;
},
children: {
name: "James",
getName: function() {
return this.name;
}
}
}
console.log("Name: ", profile.getName()); //Harry

Here, this inside the getName function refers to the profile object, so it returns the value of name from the profile object, which is "Harry."

Now if you try to access it’s parent object which is children and try to access children object’s getName method as below:

console.log("Name", profile.children.getName()); //James

Here, this inside the getName function refers to the children object, so it returns the value of name from the children object, which is "James."

The behaviour of this is determined by the context in which a function is invoked. When a function is part of an object and is called as a method on that object, this refers to the object itself.

If you convert these functions to arrow functions, the behavior of this will change because arrow functions do not have their own this binding. Instead, they inherit the this value from the enclosing scope. Let's update the code:

const profile = {
name: "Harry",
getName: ()=> {
console.log("this: profile", this);
return this.name;
},
children: {
name: "James",
getName: ()=> {
console.log("this: profile -> children", this);
return this.name;
}
}
}

console.log("Name ", profile.getName());
console.log("Child ", profile.children.getName());

In arrow functions, this is not bound to the object itself. Instead, it retains the value of this from the surrounding scope, which, in this case, is likely to be the global/window object. Therefore, both profile.getName() and profile.children.getName() will output undefined.

Creating a Reference to profile.getName: Here, we are creating a reference to the getName method of the profile object. However, note that we are not calling it immediately; we are just creating a reference to the function.

const profile = {
name: "Harry",
getName: function() {
return this.name;
},
children: {
name: "James",
getName: function() {
return this.name;
}
}
}

const userProfile = profile.getName;
console.log("Name ", profile.getName());
console.log("Name ", userProfile());

console.log("Name ", userProfile()): Here, you are calling the userProfile function, which is a reference to the profile.getName method. However, when you call it separately like this (not as a method of an object), the this value inside the function will be the global object, I ran the same code in code pen editor(https://codepen.io/), here the global object points to “CodePen”.

and “ ” blank, incase of console.

Incase we try to run this in strict mode, it will return an error:

If we have a variable which we declared globally then same code will behaves as below:

var name = "Hermione";
var profile = {
name: "Harry",
getName: function() {
return this.name;
},
children: {
name: "James",
getName: function() {
return this.name;
}
}
}

var userProfile = profile.getName;
console.log("Name ", profile.getName()); // Harry
console.log("Name ", userProfile()); // Hermione

And for strict mode “use strict” it will still return us the same error as “this” points to the undefined in strict mode in case of object reference:

2. Alone, this refers to the global object.

When used in a global context, outside of any function or object, this refers to the global object. In a web browser environment, the global object is usually the window object. In Node.js, it might be the global object.

console.log(this === window); // Output: true

In this example, when this is used outside of any function or object, it refers to the global object (window in a browser). This is the default behavior in non-strict mode. In strict mode, this would be undefined in such cases.

3. In a function, this refers to the global object and In a function, in strict mode, this is undefined.

Strict mode introduces various changes to JavaScript’s behavior to catch common coding errors and prevent the usage of certain error-prone features. The handling of this in functions is one such aspect where strict mode provides a more predictable and less error-prone behaviour.

4. In an event, this refers to the element that received the event.

When a JavaScript event occurs, such as a click, mouseover, or keypress, the this keyword inside the event handler function refers to the DOM element that received the event. This behaviour helps you work with the specific element that triggered the event.

<button id="myButton">Login</button>
<script>
const buttonElement = document.getElementById("myButton");

buttonElement.addEventListener("click", function(event) {
console.log("Event", event);
console.log("This", this);
});

</script>

Note: If you want this to refer to the button element, it's recommended to use an event listener in JavaScript instead of an inline event handler.?

In the above example, when the button is clicked, the click event of button is called, and within that function, this refers to the button element (<button>). This behaviour allows you to interact with the specific element that triggered the event. In this case, it will print both the consoles.

Incase of inline event handler, which means if you add a function within the HTML which is triggerClickEvent , In this case, this inside the function refers to the global object (window in a browser context).

<button onclick="triggerClickEvent(event)">Login</button>
<script>
function triggerClickEvent(event) {
console.log("Event", event);
console.log("This", this);
}
</script>

5. In a Class Context, the behaviour of the this keyword depends on how methods are invoked within the class. In a class, this generally refers to the instance of the class on which the method is called.
Here is the link for detail description with examples:

https://gurindernarang.medium.com/this-keyword-in-js-part-2-in-case-of-classes-bdc4231a2ef

Some other examples to test this keyword’s behaviour:

const shape = {
radius: 10,
diameter() {
return this.radius * 2;
},
perimeter: () => 2 * Math.PI * this.radius,
};

console.log(shape.diameter()); // 20
console.log(shape.perimeter()); //NAN
const person = { name: 'Lydia' };

function sayHi(age) {
return `${this.name} is ${age}`;
}

console.log(sayHi.call(person, 21));// Lydia is 21
console.log(sayHi.bind(person, 21));// function
const person = {
firstName: 'Lydia',
lastName: 'Hallie',
pet: {
name: 'Mara',
breed: 'Dutch Tulip Hound',
},
getFullName() {
return `${this.firstName} ${this.lastName}`;
},
};

console.log(person.pet?.name); //Mara
console.log(person.pet?.family?.name); //undefined
console.log(person.getFullName?.()); //Lydia Hallie
console.log(member.getLastName?.()); //ReferenceError: member is not defined
function greet() {
console.log(`Hello, ${this.name}!`);
}

const person = { name: 'Alice' };
person.greet = greet;

person.greet(); // Output: Hello, Alice!

In summary, understanding the context in which a function is called is crucial for correctly interpreting the value of this in JavaScript. It's important to be aware of the different scenarios and how they affect the behaviour of this keyword in your code.

Here are few other links which will cover behaviour of this for classes and how this will use with call, bind and apply.

Thanks for Reading!!!

--

--

No responses yet

Write a response