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
const _ = require('lodash');
let fun = function (Geeks) {
return 'Company Name : ' + this.Company
+ '\nAddress : ' + this.Address
+ '\nContact : ' + this.Contact
};
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
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
Reference: https://docs-lodash.com/v4/bind/
Learn to code easily with our course
Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
09 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...