Bind Method Javascript
-
What is
bindkeyword?- The
bind()method creates a new function that, when called, has itsthiskeyword set to provided value. - It also allows you to partially apply arguments to the function.
- The
-
Example 1:
const person = { firstName: "John", lastName: "Doe", getFullName: function() { return this.firstName + ' ' + this.lastName; }, }; const logFullName = person.getFullName.bind(person); logFullName(); // outputs: "John Doe" -
Example 2:
var obj = { name: "Chaitanya" };
function sayHello(age, profession) {
return "Hello " + this.name + " is " + age + " and is an " + profession;
}
const bindFunc = sayHello.bind(obj);
console.log(bindFunc(22, "Software Engineer"));
console.log(bindFunc(22, "Bodybuilder"));