The bind()
method in JavaScript allows you to create a new function with a specified this
value and optional arguments. By binding a function to a specific object, you can ensure that the this
value inside the function is set correctly.
Here’s the syntax for using the bind()
method:
function.bind(thisArg[, arg1[, arg2[, ...]]])
The bind()
method is available on all JavaScript functions, and it allows you to explicitly set the this
value within the function body. By default, when a function is called, the this
value is determined by how the function is invoked. However, sometimes you may want to explicitly set the this
value regardless of how the function is called.
function functionName(arg1, arg2) {
// function body
}
var boundFunction = functionName.bind(thisValue, arg1, arg2);
thisArg
: This is the value that will be set as thethis
value when the bound function is called. It determines the context in which the original function will be executed.arg1
,arg2
, …: These are optional arguments that will be passed to the original function when the bound function is invoked. You can include as many arguments as needed.
JavaScript bind() method example
Simple example code.
var person = {
name: "John",
age: 30,
greet: function (message) {
console.log(message + ", my name is " + this.name + " and I am " + this.age + " years old.");
}
};
var greetFunction = person.greet;
greetFunction("Hello");
var boundGreetFunction = person.greet.bind(person);
boundGreetFunction("Hi");
Output:
By using bind()
, we can explicitly bind a specific object as the this
value for a function, allowing us to control the context in which the function is executed.
Comment if you have any doubts or suggestions on this JS method topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version