For today I thought I would write a post on _.bind in lodash, and also the concept of binding in general, by also covering the native Function.bind as well. In this post I will be mainly writing about bind in an environment where lodash is part of the stack, and as such _.bind is available. However I will also link to other relavent content that I have written in the past that elaborates on this more.
For a basic example of bind I made a quick example that just involves a single object that contains some properties, and a stand alone method that can do something with thous properties if it where part of the objects prototype, but it is not. There are a number of ways I can get the method to work with the object, one would be to furnish a class, and make the method part of the objects prototype object. Another way would be to mutate the method as to accept the object as an argument, and use that object in place of the this keyword. However another way would be to use call, apply, or for the sake of this post bind.
The native Function.prototype.bind method works in more or less the same manor _.bind. Sense bind is a prototype method functions, I only need to call it off the function I want to bind with, and pass the object that I want to use in place of the this keyword.
So then bind is one of many ways to go about using a prototype method of a class with any object, assuming of course that it just happens to have the properties that are needed in order for that method to function properly. For example an Array method can be used with a plain old object, but it will still need to exist in a form that is similar to that of an array.
So in any situation in which I want to get a method to work with an object, I can get it to work as long as it has the proper properties and values in order for it to function.
When using a method like settimeout a function is passed as the first argument, followed by a delay in milliseconds. When doing so I am just passing the function, and what is attached to that function, not the parent object that it may be a part of. This might result in unexpected behavior in some examples.
This is because of the nature of the this keyword, and that when passing a method to settimeout the value of the this keyword is no longer a reference to the user object, but to the instance of settimeout.
So if bind is not to be used, another way of getting this to work would be to append to the instance of settimeout that is returned when calling it.