The this keyword links code, context, and object reference in JavaScript. You can use it to refer to the owner of the code.
Understand What is the this Keyword in JavaScript
The this keyword points to the object that runs the code. It gives you a way to refer back to that object inside a function.
You can use this inside a function. That allows you to write it like this.property or this.method().
It enables you to access object data from inside methods and keeps code in context, and helps you to reuse.
You have to avoid this when you want to run code in a strict, global context. That prevents confusion from a wrong reference.
Here is a quick example:
function showName() {
console.log(this.name);
}You call showName() on an object. That gives you this.name. That runs in that object context.
Use this in Object Methods
You can run this in the global code. That binds to the global object (like window in a browser). It gives you a loose reference and is not safe in strict code.
The this refers to that object. That lets method access the object’s data. It runs the method on an object
Here is an example:
const user = {
name: 'Ali',
greet() {
console.log('Hello, ' + this.name);
}
};
user.greet();The greet function on the user object logs “Hello, Ali”. this binds to the user, so it uses the user name.
For another example:
const pet = {
type: 'dog',
getType() {
return this.type;
}
};
const result = pet.getType();
console.log(result);You call getType on pet. That returns ‘dog’. this binds to the pet so it returns the pet’s type.
Use this in Arrow Functions
Arrow functions do not bind this. They inherit this from outside. That gives you a stable reference inside nested code.
Here is an example:
const group = {
name: 'Team',
showLater() {
setTimeout(() => {
console.log(this.name);
}, 100);
}
};
group.showLater();You run showLater. Arrow inside setTimeout uses this from showLater. That refers to a group, and it logs ‘Team’.
Use this in Event Handlers
In events, this refers to the element that runs the code. That lets you change element data from code.
For example:
button.onclick = function () {
this.textContent = 'Clicked';
};You click the button. handler to run on the element. this points to that element which changes its label to ‘Clicked’.
How to Change this Keyword with call, apply, and bind in JavaScript
You can use call or apply to change this when you run a function. That lets you pass an object as context. Also, you can use bind to lock this to that object for later.
Here is an example for the “call”:
function sayCity() {
console.log(this.city);
}
sayCity.call({city: 'Riyadh'});The call sets this.city to ‘Riyadh’ which prints ‘Riyadh’.
apply example:
function sayFull(char1, char2) {
console.log(this.name + char1 + char2);
}
sayFull.apply({name: 'Bob'}, ['!', '?']);The apply function sets this.name to ‘Bob’. That prints ‘Bob!?’. Those uses apply to pass-by-array.
bind example:
const showColor = function () {
console.log(this.color);
}.bind({color: 'red'});
showColor();
The bind object with color locks this to object. That prints ‘red’.
Examples of this Keyword in JavaScript
Method on nested object:
const car = {
brand: 'Toyota',
engine: {
getBrand() {
console.log(this.brand);
}
}
};
car.engine.getBrand();This prints undefined. this points to the engine, not the car. That shows nested context does not inherit the parent object.
Borrow method:
const obj1 = {
val: 5,
getVal() {
return this.val;
}
};
const obj2 = {val: 10};
console.log(obj1.getVal.call(obj2));This logs 10. You borrow getVal from obj1. You set this to obj2. That shows you can reuse a method for another object.
Bind in callback:
const counter = {
count: 0,
inc() {
this.count++;
console.log(this.count);
}
};
setInterval(counter.inc.bind(counter), 1000);This logs numbers each second. You bind counter. That keeps this inside inc correct.
Wrapping Up
In this article, you learned this keyword and how it works.
Here is a quick recap:
- The
thislinks code to object. - You use methods to set it in an object.
- Arrow uses outer context.
- Events use an element as context.
- call/apply/bind let you override context.
FAQs
What is JavaScript this keyword?
The this keyword in JavaScript refers to the object that is executing the current code. Its value changes based on the context.
Table of Content
const obj = {
name: "Alex",
greet: function() {
console.log(this.name);
}
};
obj.greet(); // Output: Alex
thisrefers to global object in global scopethisrefers to the object inside object methods
How does JavaScript this work in functions?
Inside normal functions, this depends on how the function is called. In strict mode it is undefined.
function showName() {
console.log(this);
}
showName(); // Window in browsers or undefined in strict mode
- Function call without object → global or undefined
- Method call inside object → object reference
What is the difference between arrow function and normal function with this?
An arrow function does not have its own <this>. It inherits <this> from the surrounding scope.
const obj = {
name: "Sam",
normal: function() { console.log(this.name); },
arrow: () => { console.log(this.name); }
};
obj.normal(); // Output: Sam
obj.arrow(); // Output: undefined
Key Point: Arrow functions should not be used as methods when this is required.How to change the value of JavaScript this?
You can control <this> using call, apply, or bind.
function greet() {
console.log("Hi " + this.name);
}
const person = { name: "John" };
greet.call(person); // Hi John
greet.apply(person); // Hi John
const bound = greet.bind(person);
bound(); // Hi John
- call passes arguments directly
- apply passes arguments as an array
- bind returns a new function with fixedthis
Similar Reads
The current essay is devoted to the basic principles and introduction of JavaScript. This language no longer needs to be…
String Operators in JavaScript help you work with text. You can join, build, or change strings. Most of what you…
JavaScript Math.tan() finds the tangent of an angle in radians. You use it when you need to solve angle-based math.…
This guide shows how toSorted function works in JavaScript with arrays. It covers syntax, rules, and examples for numbers, text,…
The JavaScript unshift function adds one or more elements at the start of an array. It shifts existing items to…
If you are ready to take your first steps into the realm of web development, then there cannot be a…
JavaScript arithmetic operators let you add, subtract, multiply, or divide numbers. You can also use them to find remainders or…
The development of full-featured and interesting pages cannot be done without JavaScript which makes it possible to animate plain HTML…
Arrow function gives you short code and keeps this in the right scope in JavaScript. Understand the Arrow Function in…
Some numbers come from user input and other come from math operations. Sometimes, these numbers need to stay positive. The…