JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Function bind()

14 April 2025 | Category:

The bind() method in JavaScript is used to create a new function that, when called, has its this keyword permanently set to a specific value.

Unlike call() and apply(), which invoke the function immediately, bind() returns a new function that you can call later.


✅ Syntax

function.bind(thisArg, arg1, arg2, ...)

Parameters:

  • thisArg – The value you want this to refer to.
  • arg1, arg2, ... – Optional arguments that are prepended to arguments passed when the bound function is called.

🔍 Example: Basic Usage

const person = {
  name: "Dev",
};

function greet() {
  console.log("Hello, " + this.name);
}

const greetPerson = greet.bind(person);
greetPerson(); // Output: Hello, Dev

Even though greet() is a standalone function, bind() locks this to the person object.


⚙️ Pre-filling Arguments (Partial Application)

You can also use bind() to preset some arguments:

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

const double = multiply.bind(null, 2);
console.log(double(5)); // Output: 10

Here, a is fixed as 2, and we just need to pass b.


⏱ Real-World Use Case: Event Handlers

In event handlers, this often refers to the DOM element. You can use bind() to attach your own object as this:

function showMessage() {
  alert(this.message);
}

const obj = { message: "Hello from bind!" };
const boundFunc = showMessage.bind(obj);

document.getElementById("btn").addEventListener("click", boundFunc);

❗ Important Notes

FeatureDescription
ReturnsA new function with this bound permanently
Not calledbind() does not call the function immediately
PermanentOnce bound, this can’t be changed by call() or apply()

🤝 bind() vs call() vs apply()

MethodWhen to UseArguments FormatExecutes Function Immediately?
call()Set this & call instantlyComma-separated✅ Yes
apply()Set this & call instantlyArray of arguments✅ Yes
bind()Set this & call laterComma-separated❌ No (returns new function)

🧾 Summary

  • bind() creates a new function with this permanently set.
  • Useful when passing methods as callbacks or in event listeners.
  • Allows partial function application by pre-setting arguments.