Lodash _.bind() Method

The Lodash _.bind() method is used to create a function that will invoke the given function with the this 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)

Parameter: 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.

The below example illustrates the Lodash _.bind() method:



Example 1:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Acquiring lodash variable
const _ = require('lodash'); 
  
// Function
var fun = function(Geeks) { 
    return 'Company Name : ' + this.Company 
        + '\nAddress : ' + this.Address 
        + '\nContact : ' + this.Contact 
}; 
    
// Use of bind() function
var func = _.bind(fun, { 
    Company: 'GeeksforGeeks'
    Address: 'Noida'
    Contact: '+91 9876543210' 
}); 
    
console.log(func());

chevron_right


Output:

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

Example 2:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Lodash variable
const _ = require('lodash'); 
  
var obj = { 
    Name: "GeeksforGeeks"
    Address: "Noida" 
}; 
    
var fun = function (Geeks) { 
    return 'Welcome to ' + this.Name 
        + '\nAddress: ' + this.Address 
};
    
var func = _.bind(fun, obj); 
   
console.log(func());

chevron_right


Output:

Welcome to GeeksforGeeks 
Address: Noida

Reference: https://docs-lodash.com/v4/bind/

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.