Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Function Bind in JavaScript

Function Bind in JavaScript

? Function.prototype.bind() in JavaScript


What is bind()?

  • bind() creates a new function with a fixed this context and optionally prepends arguments.

  • It does not call the function immediately but returns a new function you can call later.

  • Useful to lock the value of this for functions used as callbacks or event handlers.


Syntax

const boundFunc = func.bind(thisArg[, arg1[, arg2[, ...]]]);
  • thisArg: The value to bind as this.

  • arg1, arg2, ...: Optional arguments to prepend to the new function.


Example 1: Binding this

const person = {  name: "John",  greet() {    console.log("Hello, " + this.name);  }};const greet = person.greet;greet();  // undefined or global contextconst boundGreet = person.greet.bind(person);boundGreet();  // Hello, John

Example 2: Partial Application (Pre-filling Arguments)

function multiply(a, b) {  return a * b;}const double = multiply.bind(null, 2);console.log(double(5));  // 10console.log(double(10)); // 20

Key Points

  • bind() returns a new function.

  • It does not invoke the original function immediately.

  • It fixes the this context for the new function.

  • You can also fix some initial arguments (partial application).


Difference Between bind(), call(), and apply()

MethodCalls Function Immediately?Arguments FormatReturns New Function?
call()YesComma-separatedNo
apply()YesArray or array-likeNo
bind()NoComma-separated (pre-filled)Yes

Summary Table

Featurebind()
Returns new function?
Fixes this context?
Partial arguments?
Calls immediately?

Want to see how bind() is used in event handlers or how to create your own bind function polyfill?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql