In JavaScript, the
thiskeyword refers to the object that is currently executing the code. Its value depends on how a function is called, not where it’s written.
➡️ this refers to the object before the dot → user
const user = {name: "Daniel",sayHi() {console.log(this.name);}};user.sayHi();
windowundefinedfunction show() {console.log(this);}show(); // window (browser) or undefined (strict mode)
this.this from the surrounding scope.const user = {name: "Daniel",sayHi: () => {console.log(this.name);}};user.sayHi(); // undefined
➡️ this is NOT user here
button.addEventListener("click", function () {console.log(this); // button element});
➡️ this refers to the element that fired the event
function greet() {console.log(this.name);}const user = { name: "Daniel" };greet.call(user); // Danielgreet.apply(user); // Danielconst bound = greet.bind(user);bound(); // Daniel
| Method | Calls Function Now? | How args are passed | Returns new function? |
|---|---|---|---|
| call | ✅ Yes | One by one | ❌ No |
| apply | ✅ Yes | Array | ❌ No |
| bind | ❌ No | One by one | ✅ Yes |
| Situation | What this is |
|---|---|
| Object method | The object |
| Regular function | window or undefined |
| Arrow function | Inherited from outer scope |
| Event handler (function) | The DOM element |
| call/apply/bind | Explicitly set |