Question 45

Question

Explain how to use bind, call, and apply methods together with new operator.

Answer

bind, call, and apply give you fine-grained control over how functions execute, especially when dealing with the this keyword and constructor functions. Let's break it down:

1. new Operator (Constructor Functions):

  • Used to create new instances of objects (objects are based on function blueprints called "constructor functions").

  • When you use new, it does several things automatically:

    • Creates a new empty object.

    • Sets the newly created object's internal [[Prototype]] property to point to the prototype of the constructor function. This lets the object inherit properties and methods from its constructor.

    • Calls the constructor function, passing in this as the newly created object itself (which is key for modifying properties within the constructor).

Example:

function Animal(name) {
  this.name = name;
}

Animal.prototype.speak = function() {
  console.log(`${this.name} makes a sound!`); 
};

const dog = new Animal("Fido");
dog.speak(); // Output: "Fido makes a sound!"

2. bind(context, arg1, arg2, ...): Creates a new function that has its this value permanently set to the specified context. You can also pre-provide arguments for the new function.

Example:

function greet(greeting) {
  console.log(`${greeting}, ${this.name}!`); 
}

const person = { name: "Alice" };

const boundGreet = greet.bind(person, "Hello");
boundGreet(); // Output: "Hello, Alice!"

3. call(context, arg1, arg2, ...): Executes a function immediately, and explicitly sets the this value to the provided context. You pass arguments directly after context.

Example:

function greet(greeting) {
  console.log(`${greeting}, ${this.name}!`); 
}

const person = { name: "Bob" };

greet.call(person, "Howdy"); // Output: "Howdy, Bob!"

4. apply(context, [argsArray]): Similar to call, but you pass arguments as an array instead of individual values.

Example:

function sum() {
  let total = 0;
  for (let i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }
  return total;
}

const numbers = [1, 2, 3, 4];
console.log(sum.apply(null, numbers)); // Output: 10

bind, call, and apply with new:

  • You rarely use these methods directly with the new operator.

  • The primary reason is that new already handles binding this within its own execution context for constructor functions.

Last updated