Open In App

Lodash _.bind() Method

Last Updated : 03 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Lodash _.bind() method is used to create a function that invokes the given function with the binding of thisArg and it is used to bind a function to an object. When the function is called, the value of this will be the object. The _.bind.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder for partially applied arguments.

Syntax:

_.bind(func, thisArg, partials)

Parameters:

This method accepts three parameters as mentioned above and described below:

  • func: This parameter holds the function that will bind.
  • thisArg: This parameter holds the object elements.
  • partials: This parameter needs to add some symbols between the elements.

Return value:

  • This method returns a new bound function.

Example 1: In this example, the code uses the Lodash library to bind a function to a specific context and then calls the bound function to display company information.

JavaScript
// Acquiring lodash variable
const _ = require('lodash');

// Function
let fun = function (Geeks) {
    return 'Company Name : ' + this.Company
        + '\nAddress : ' + this.Address
        + '\nContact : ' + this.Contact
};

// Use of bind() function
let func = _.bind(fun, {
    Company: 'GeeksforGeeks',
    Address: 'Noida',
    Contact: '+91 9876543210'
});

console.log(func()); 

Output:

Company Name : GeeksforGeeks 
Address : Noida
Contact : +91 9876543210

Example 2: In this example, the code demonstrates Lodash's _.bind for function context binding and displays a welcome message with company details in the console.

JavaScript
// Lodash variable
const _ = require('lodash'); 

let obj = { 
    Name: "GeeksforGeeks", 
    Address: "Noida" 
}; 
  
let fun = function (Geeks) { 
    return 'Welcome to ' + this.Name 
        + '\nAddress: ' + this.Address 
};
  
let func = _.bind(fun, obj); 
 
console.log(func()); 

Output:

Welcome to GeeksforGeeks 
Address: Noida

Next Article

Similar Reads