Difference between .bind
and .call
and .apply
.call
takes in comma-separated arguments as the next arguments
.apply
takes in an array of arguments as the next argument
function add(a, b) {
return a + b;
}
console.log(add.call(null, 1, 2)); // 3
console.log(add.apply(null, [1, 2])); // 3
.bind
is useful for binding the value of this
that we want to pass to other functions, note that .bind
does not execute the function, it returns a copy of the bound function
const person = {
name: "John",
};
function sayHi() {
console.log(`Hi, my name is ${this.name}`);
}
console.log(sayHi.bind(person)); // function
console.log(sayHi.call(person)); // Hi, my name is John