JavaScript Function bind()

The bind() method allows an object to borrow a method from another object without copying.

Example


bind() Syntax

The syntax of the bind() method is:

func.bind(thisArg, arg1, ... argN)

Here, func is a function.


bind() Parameters

The bind() can take two parameters:

  • thisArg - The value provided as this parameter for func.
  • arg1, ... argN (optional) - The value of arguments present inside func.

Notes: If thisArg is not specified, the this of the executing scope is treated as thisArg.


bind() Return Value

  • Returns a copy of the given function with the specified this value, and initial arguments (if provided).

Example 1: Using bind() Method

Output

Jimmy studies in grade 6.

In the above example, we have defined two objects student1 and student2.

Since student2 doesn't have the introduction() method, we are borrowing it from student1 using the bind() function.

student1.introduction.bind(student2) returns the copy of introduction() and assigns it to result.


Example 2: Using bind() Method with two Parameters

Output

Jimmy scored 95 in an exam.

In the above example, we have passed two parameters thisArg and arg1 in bind().

The student2 object is passed as this parameter and 95 is passed as an argument for the score parameter.


Recommended Reading: JavaScript Function call()