Js This Keyword in JavaScript
? JavaScript this Keyword
The this keyword in JavaScript refers to the context object that the current code is executing within. It’s one of the most important and sometimes confusing parts of JavaScript.
What Does this Refer To?
The value of this depends on how a function is called:
1. Global Context
In the global execution context (outside any function), this refers to the global object:
In browsers:
windowIn Node.js:
global
console.log(this); // window (in browser)2. Inside a Function
In non-strict mode,
thisinside a regular function refers to the global object (windowin browsers).In strict mode,
thisisundefined.
function show() { console.log(this);}show(); // window (non-strict) or undefined (strict mode)3. As a Method of an Object
When a function is called as a method of an object, this refers to that object.
const person = { name: "Alice", greet() { console.log(this.name); }};person.greet(); // Output: Alice4. In a Constructor Function
When a function is used as a constructor with new, this refers to the newly created object.
function Person(name) { this.name = name;}const p = new Person("Bob");console.log(p.name); // Bob5. With call(), apply(), and bind()
You can explicitly set this with these methods:
function say() { console.log(this.name);}const user = { name: "Charlie" };say.call(user); // Charliesay.apply(user); // Charlieconst boundSay = say.bind(user);boundSay(); // Charlie6. Arrow Functions
Arrow functions do not have their own this. Instead, this is inherited lexically from the enclosing scope.
const obj = { name: "Dana", greet: () => { console.log(this.name); }};obj.greet(); // undefined (or window.name)Because arrow functions don’t bind their own this, they’re often used to preserve the this context in callbacks.
Summary Table
| Context | this refers to |
|---|---|
| Global scope | global object (window/global) |
| Function call (non-strict) | global object |
| Function call (strict mode) | undefined |
| Method call | the object owning the method |
Constructor (new) | the newly created object |
call/apply/bind | explicitly defined object |
| Arrow function | this from surrounding scope |
If you want, I can show you examples demonstrating tricky this behavior!