Skip to main content

this Keyword in JavaScript (Live Playground)

In this tutorial, we will explore the this keyword in JavaScript. You will learn about its context-dependent nature and how to use it effectively in various situations.

What is this?

In JavaScript, the this keyword refers to the context in which a function is called. The value of this depends on how the function is called and can be different in various situations.

this in a Regular Function

In a regular function, the value of this refers to the global object (window in a browser environment or global in a Node.js environment).

function regularFunction() {
console.log(this);
}

regularFunction(); // Output: Window {...}
Live Playground, Try it Yourself

this in an Object Method

In an object method, the value of this refers to the object that the method belongs to.

const person = {
name: 'John',
greet: function () {
console.log('Hello, my name is ' + this.name + '.');
},
};

person.greet(); // Output: Hello, my name is John.
Live Playground, Try it Yourself

this in an Event Listener

In an event listener, the value of this refers to the HTML element that the event is attached to.

<button id="myButton">Click me</button>
<script>
const button = document.getElementById("myButton");
button.addEventListener("click", function () {
console.log(this); // Output: <button id="myButton">Click me</button>
});
</script>

Live Playground, Try it Yourself

Changing the Context of this

In JavaScript, you can change the context of this using the call, apply, and bind methods.

Using call

The call method allows you to call a function with a specified this value and arguments.

function greet(greeting) {
console.log(greeting + ', my name is ' + this.name + '.');
}

const john = { name: 'John' };
greet.call(john, 'Hi call'); // Output: Hello, my name is John.

Using apply

The apply method is similar to call, but it takes an array of arguments instead of separate arguments.

greet.apply(john, ['Hi apply']); // Output: Hello, my name is John.

Using bind

The bind method creates a new function with a specified this value and optional arguments.

const greetJohn = greet.bind(john, 'Hi bind');
greetJohn(); // Output: Hi, my name is John.
Live Playground, Try it Yourself

Conclusion

The this keyword in JavaScript is a powerful and versatile feature. By understanding its context-dependent nature and how to change its context using call, apply, and bind, you can write more flexible and efficient JavaScript code.