“ Let’s Understand bind() in javascript ”

By this method , we can bind an object to a common function
— Bind Method returns a new Function —
Syntax : let new_function = function.bind(object)
let _obj ={
first_name:"xyz",
last_name:"zyx"
}function print(){
console.log(`firstName : ${this.first_name} lastName : ${this.last_name}`)
}let new_function = print.bind(_obj)new_function();
This is how we bind a function to an object using bind() method , we can also pass arguments in bind method
let _obj ={
first_name:"xyz",
last_name:"zyx"
}function print(title){
console.log(`${title} . firstName : ${this.first_name} lastName : ${this.last_name}`)
}let new_function = print.bind(_obj,"Mr")new_function();
Now let us take an example of using bind() method for a function inside an object
Syntax : let new_function = object.method.bind(new_object)
let fruits = {
type : "Fruit",
fruit_says : function(f){
console.log(` ${f} is a ${this.type}`)
}
}let veggie = {
type : "Vegetable",
veggie_says : function(f){
console.log(` ${f} is a ${this.type}`)
}
}let new_function = fruits.fruit_says.bind(veggie,"apple")new_function()/*OUTPUT:
apple is a Vegetable*/