Module 4: Functions, Scope, and Closures
this, call, apply, and bind
Understand how regular function calls determine this and how to control the receiver.
For regular functions, this generally depends on how the function is called. A method call such as user.describe() sets this to the receiver object for that call. A standalone function call behaves differently, and strict mode prevents the old substitution of the global object for a missing receiver. Arrow functions capture this lexically.
const user = {
name: "Ravi",
describe() {
return `User: ${this.name}`;
},
};
console.log(user.describe());
If you extract the method into a variable, the receiver is not automatically preserved:
const describeUser = user.describe;
// describeUser() does not retain user as its receiver.
call, apply, and bind#
call invokes a function with a chosen this and positional arguments. apply does the same while accepting arguments in an array-like value. bind creates a new function with a permanently bound receiver and, optionally, preset arguments.
function introduce(city) {
return `${this.name} lives in ${city}`;
}
const person = { name: "Mina" };
console.log(introduce.call(person, "Bengaluru"));
const introduceMina = introduce.bind(person);
Practical advice#
Use method syntax when a function naturally belongs to an object. Use arrow functions for callbacks that should inherit the surrounding this, but do not use them as object methods merely because they are shorter.
Practice#
Create a method that reads this.name; compare a direct method call with a detached call and then use bind to retain the receiver.