this
refers to the object that is calling the function.
It depends on how the function is invoked, not where it is defined.
Where You Use this |
What It Refers To |
---|---|
console.log(this) global context | window in browser |
Inside an object method | The object calling the method. |
Inside a regular function | Depends on how the function is called (global or undefined in strict mode). |
In a constructor function (new ) |
The new object being created. |
With call or apply |
Whatever object you explicitly set as this . |
Inside an arrow function | Inherits this from the surrounding scope. |
Feature | call | apply | bind |
---|---|---|---|
Invocation | Invokes the function immediately | Invokes the function immediately | Returns a new function (not invoked) |
Arguments | Passed individually | Passed as an array | Can pre-fill arguments (partial application) |
Use Case | When you know arguments beforehand | When arguments are in an array | When you want to create a reusable function |
You can use call
, apply
, or bind
to borrow methods from one object to use on another.
Example with call
:
const person1 = { name: 'Alice' };
const person2 = { name: 'Bob' };
function introduce() {
console.log(`Hi, I'm ${this.name}`);
}
introduce.call(person1); // Output: Hi, I'm Alice
introduce.call(person2); // Output: Hi, I'm Bob
apply
for Array ManipulationMath.max
doesn’t work directly with arrays, but apply
can help.
const numbers = [3, 7, 2, 8];
const max = Math.max.apply(null, numbers);
console.log(max); // Output: 8
Here:thisArg
is null
because Math.max
doesn’t use this
.
bind
You can use bind
to create a function with pre-filled arguments.
function multiply(a, b) {
return a * b;
}
const double = multiply.bind(null, 2); // Pre-filling `a` with 2
console.log(double(5)); // Output: 10
Still will continue to study more.