bind() Method in JavaScript

Ashwings
1 min readDec 15, 2020

--

“ Let’s Understand bind() in javascript ”

image of 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
*/

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ashwings
Ashwings

No responses yet

Write a response