call, apply, and bind are function methods that allow you to control the execution context ([this]) and parameters:
function greet(greeting, punctuation) {
return greeting + ', ' + this.name + punctuation;
}
const person = { name: 'John' };
greet.call(person, 'Hello', '!'); // 'Hello, John!'
greet.apply(person, ['Hello', '!']); // 'Hello, John!'
const boundGreet = greet.bind(person, 'Hello', '!');
boundGreet(); // 'Hello, John!'call, apply, and bind are methods that allow you to “dress” a function in different “costumes” (contexts). Imagine you have a universal remote control that you can connect to different devices. 🎮
These are special methods that all functions have. They allow you to control what [this] will be inside a function.
function introduce(age, city) {
return 'My name is ' + this.name + ', I am ' + age + ' years old, I am from ' + city;
}
const person = { name: 'John' };
// Call function in person context
introduce.call(person, 25, 'Moscow');
// 'My name is John, I am 25 years old, I am from Moscow'const person = { name: 'John' };
// Same parameters, but in array
introduce.apply(person, [25, 'Moscow']);
// 'My name is John, I am 25 years old, I am from Moscow'const person = { name: 'John' };
// Create new function with fixed context
const boundIntroduce = introduce.bind(person, 25, 'Moscow');
// Now can be called without parameters
boundIntroduce(); // 'My name is John, I am 25 years old, I am from Moscow'function sum(a, b, c) {
return this.base + a + b + c;
}
const obj = { base: 10 };
// call — arguments comma-separated
sum.call(obj, 1, 2, 3); // 16
// apply — arguments in array
sum.apply(obj, [1, 2, 3]); // 16function multiply(a, b) {
return this.factor * a * b;
}
const obj = { factor: 10 };
// bind creates new function, but doesn't call it
const boundMultiply = multiply.bind(obj, 2);
// Now boundMultiply is a new function
boundMultiply(3); // 60 (10 * 2 * 3)// Good when you know all parameters
func.call(context, arg1, arg2, arg3);// Convenient when parameters come in array
const args = [1, 2, 3];
func.apply(context, args);// Create function with fixed context
const logUser = console.log.bind(console, 'User:');
logUser('John'); // 'User: John'function calculate(a, b) {
return this.multiplier * (a + b);
}
const obj = { multiplier: 10 };
// ❌ Wrong — apply expects array
// calculate.apply(obj, 5, 3); // Error!
// ✅ Correct
calculate.apply(obj, [5, 3]); // 80
// ✅ Or use call
calculate.call(obj, 5, 3); // 80function greet() {
return 'Hello, ' + this.name;
}
const person = { name: 'John' };
// ❌ Forgot to call bind
const boundGreet = greet.bind(person); // This is a function!
// boundGreet; // Won't call function
// ✅ Need to call
boundGreet(); // 'Hello, John'Understanding these methods helps flexibly control function context and parameters. This is very useful when working with objects and methods! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪