Sobes.tech
Middle

Mida teeb ja milleks on vaja funktsiooni function.prototype.bind?

sobes.tech AI

Vastus AI-lt

function.prototype.bind creates a new function that, when called, has its this value (i.e., call context) set to a specific value and optionally pre-fixes a set of arguments that precede those passed during the call.

What is it used for:

  1. Fixing the context (this): Especially useful in asynchronous operations, event handlers, or when passing object methods as callbacks, where the default behavior of this might change. bind ensures that the method executes in the context of the original object.
  2. Partial application of functions (Currying): Allows creating a new function with some initial arguments fixed from the original function.

Example of fixing context:

class MyClass {
  constructor() {
    this.name = 'MyClass Instance';
  }

  greet() {
    console.log(`Hello from ${this.name}`);
  }
}

const instance = new MyClass();
const greetMethod = instance.greet;

// greetMethod is called in a global context (or undefined in strict mode), `this` is not MyClass
greetMethod(); // Output: Hello from undefined (or error)

const boundGreetMethod = instance.greet.bind(instance);

// boundGreetMethod is called with the context of the instance
boundGreetMethod(); // Output: Hello from MyClass Instance

Example of partial application:

function multiply(a, b) {
  return a * b;
}

const multiplyByTwo = multiply.bind(null, 2); // Fix the first argument to 2

console.log(multiplyByTwo(5)); // Output: 10 (same as multiply(2, 5))