Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter and Return Value
3.1.
Syntax: 
3.2.
Parameters:
3.3.
Return Value: 
4.
Examples 
4.1.
Binding a Method to Its Object:
4.2.
JavaScript
4.3.
Using in Event Handlers:
4.4.
JavaScript
4.5.
Asynchronous Operations:
4.6.
JavaScript
4.7.
Handling Dynamic Method Updates:
4.8.
JavaScript
5.
Frequently Asked Questions 
5.1.
How is _.bindKey() different from _.bind()?
5.2.
What happens if the object's method changes after using _.bindKey()?
5.3.
Can _.bindKey() be used for non-method properties?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.bindKey() Method

Author Gaurav Gandhi
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Managing the context of method execution within objects is a key aspect of JavaScript programming, especially when dealing with object-oriented patterns or callbacks. Lodash enriches this area with the _.bindKey() method.

Lodash _.bindKey() Method

 This function creates a bound function that invokes the method at a given key of an object, with this bound to the object itself. Moreover, it can partially apply arguments, similar to _.bind(). 

Why This Function is Used

The _.bindKey() function is particularly useful when you need to ensure that a method of an object maintains its context (this value) correctly, regardless of how it's called. This is important in scenarios like event handling, asynchronous callbacks, or when methods are passed around as first-class functions. By binding a method to its parent object, _.bindKey() ensures that the method can access the object's properties and other methods reliably.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax, Parameter and Return Value

Syntax: 

_.bindKey(object, key, [partials])

Parameters:

  • object: The object to bind and assign the method to.
     
  • key: The key of the method in the object.
     
  • [partials]: Arguments to be partially applied (fixed) in the new function.

Return Value: 

(Function) - Returns the new bound function.

Examples 

Binding a Method to Its Object:

  • JavaScript

JavaScript

var _ = require('lodash');

var user = {

 name: 'John',

 greet: function(greeting) {

   console.log(greeting + ', ' + this.name);

 }

};

var boundGreet = _.bindKey(user, 'greet', 'Hello');

boundGreet();

Output: 

'Hello, John'


Demonstrates binding a method to its owning object and partially applying an argument.

Using in Event Handlers:

  • JavaScript

JavaScript

var button = {

 label: 'Submit',

 onClick: function() { console.log(this.label + ' clicked'); }

};

var boundClickHandler = _.bindKey(button, 'onClick');

document.getElementById('submitButton').addEventListener('click', boundClickHandler);

// When the button is clicked: 

Outputs 

'Submit clicked'


Shows using _.bindKey() for event handlers to maintain the correct context.

Asynchronous Operations:

  • JavaScript

JavaScript

var asyncOperation = {

 result: 'Success',

 complete: function(callback) {

   // Simulate async operation

   setTimeout(() => callback(this.result), 1000);

 }

};

var boundComplete = _.bindKey(asyncOperation, 'complete', result => console.log(result));

boundComplete();

Output after 1 second: 

'Success'


An example of using _.bindKey() in an asynchronous operation to ensure the correct context.

Handling Dynamic Method Updates:

  • JavaScript

JavaScript

var person = {

 name: 'Alice',

 greet: function() { console.log('Hello, ' + this.name); }

};

var boundGreet = _.bindKey(person, 'greet');

// Updating the method later

person.greet = function() { console.log('Greetings, ' + this.name); };

boundGreet();

Output: 

'Greetings, Alice'


Demonstrates _.bindKey() handling updates to the method after binding.

Frequently Asked Questions 

How is _.bindKey() different from _.bind()?

While _.bind() binds a function to a specific context, _.bindKey() binds a method of an object to the object itself, ensuring that the method retains access to the object's properties.

What happens if the object's method changes after using _.bindKey()?

If the method on the object changes after _.bindKey() is used, the bound function will invoke the updated method, maintaining the binding to the current method at that key.

Can _.bindKey() be used for non-method properties?

_.bindKey() is designed for methods (functions) of objects. Using it with non-method properties will not produce meaningful results.

Conclusion

Lodash's _.bindKey() method is a valuable tool for binding methods to their parent objects, ensuring consistent context (this value) in various scenarios, including event handling and asynchronous operations. It offers flexibility in managing method execution, especially in dynamic contexts.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Lodash _.bind() Method
Next article
Lodash _.split() Method
Live masterclass