The this keyword helps you access the object that owns the current function. It lets functions know who called them.
0
0
this in functions in Javascript
Introduction
When you want a function to work with the object that called it.
When you write methods inside objects and want to use object properties.
When you want to reuse the same function for different objects.
When you want to understand how JavaScript decides the context inside functions.
Syntax
Javascript
function example() { console.log(this); }
Inside a regular function, this usually refers to the object that called the function.
In the global scope or simple function calls, this can be undefined in strict mode or the global object otherwise.
Examples
Here,
this inside greet refers to obj, so it prints 'Alice'.Javascript
const obj = { name: 'Alice', greet: function() { console.log(this.name); } }; obj.greet();
Calling
showThis as a simple function prints undefined in strict mode or the global object otherwise.Javascript
function showThis() { console.log(this); } showThis();
Here,
greetFunc is called without an object, so this is undefined and this.name is undefined.Javascript
const person = { name: 'Bob', greet() { console.log(`Hello, ${this.name}`); } }; const greetFunc = person.greet; greetFunc();
Sample Program
This program shows how this inside sayName refers to the user object, so it prints the user's name.
Javascript
const user = { name: 'Emma', sayName: function() { console.log(`My name is ${this.name}`); } }; user.sayName();
OutputSuccess
Important Notes
Arrow functions do not have their own this. They use this from the surrounding code.
Using this inside event handlers or callbacks can behave differently depending on how the function is called.
Summary
this points to the object that calls the function.
Inside object methods, this helps access object properties.
Be careful: calling a function without an object can make this undefined.