Lodash _.bind() Method
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)
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 (Beginner) { return 'Company Name : ' + this .Company + '\nAddress : ' + this .Address + '\nContact : ' + this .Contact }; // Use of bind() function let func = _.bind(fun, { Company: 'w3wiki' , Address: 'Noida' , Contact: '+91 9876543210' }); console.log(func()); |
Output:
Company Name : w3wiki
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: "w3wiki" , Address: "Noida" }; let fun = function (Beginner) { return 'Welcome to ' + this .Name + '\nAddress: ' + this .Address }; let func = _.bind(fun, obj); console.log(func()); |
Output:
Welcome to w3wiki
Address: Noida
Reference: https://docs-lodash.com/v4/bind/
Contact Us