js
CopyEdit
function show() {
console.log(this);
}
show(); // In browsers: Window (or globalThis)
When a function is called as a method of an object.
js
CopyEdit
const obj = {
name: 'JS',
greet() {
console.log(this.name);
},
};
obj.greet(); // 'JS' → `this` refers to `obj`
call() – Invoke immediately with custom thisjs
CopyEdit
const user = {
name: "Alice",
greet() {
console.log(`Hello, I'm ${this.name}`);
},
};
const admin = { name: "Bob" };
// Reuse greet from user
user.greet.call(admin); // "Hello, I'm Bob"
apply() – Same as call(), but with arguments as an arrayjs
CopyEdit
const numbers = [5, 10, 3, 8];
const max = Math.max.apply(null, numbers); // same as Math.max(...numbers)
console.log(max); // 10
This is useful when you already have args in an array (older alternative to the spread operator).
bind() – Returns a new function with locked thisthis in callbacksjs
CopyEdit
const button = {
label: "Click Me",
handleClick() {
console.log(this.label);
},
};
const unbound = button.handleClick;
unbound(); // undefined (or window)
const bound = button.handleClick.bind(button);
bound(); // "Click Me"
✅ Common in React, event handlers, and setTimeouts.