The bindAll
function of Lodash is used to bind the this
context of specified methods of an object to the object itself permanently. This ensures that the method can never be called with a different context even if it is invoked separately or passed around as a callback.
Here is an example of how to use the bindAll
function in JavaScript:
index.tsx393 chars18 lines
In the example above, we have created an object having two methods sayName
and sayAge
. We then use the bindAll
function of Lodash to bind the this
context of both these methods permanently to the object. Finally, we invoke the methods using the object's reference and setTimeout
method to showcase how they can be passed around as callbacks.
Please note that the first argument to bindAll
function must be the target object and the second argument must be an array of method names that need to be bound.
gistlibby LogSnag