So within car, you can create properties, right? What if you were to create a property with the name, oh, say… displayName
? And what might you set that to? You could, if you were so inclined, set that to something like driver.displayName
(note that, without the parenthesis, I’ve set the function itself to the object property). And that’s great and all, but there’s still the issue of context
.
Context is a big and ugly beast that has devoured many a hale and hardy javascript developer. It’s easy to lose context. What is context? When a function is called, it is called in reference to … something. If, for example, I were to call myArray.push("foo")
, I have called the object method .push()
in the context of myArray
. If I call driver.displayName()
, then I would be calling the function displayName
in the context of driver
.
But what if there were a way to run a function from somewhere else, in the context
of any other object? that would be cool, right? In fact, that’s pretty much how mixins work. A great feature, lets you take an object that you define as a means of storing a whole library of utility functions, and run them in the context of your unique object.
In your case, in the case of car
, we have a context (the car
object), and we have a a function we’re planning to pull in from somewhere else (the driver
object). How about if we were to create a property on car
that points to the method on driver
we want, but make sure it doesn’t know about the driver
context? That would be, like, AMAZING!!
And that’s what .bind()
does for us. It tells a given function, taken from somewhere else, to run in the context it is given. So we could, in fact, do something just like this:
const car = {
name: "Prius",
displayName: driver.displayName.bind(this)
}
Now, that gets into the question of what’s this
? And that’s a whole discussion. this
is, in fact, the current context. In the above block of code, this
refers to the car
object that we’ve defined. By binding a function from somewhere else to a variable in the local context, we tell it to run as though it were a local function to our car
object.
Pretty neat, and confusing as ANYTHING. Best place to research things like this? As @husseyexplores has suggested, MDN is a very powerful, very complete resource. Also, and one I highly recommend as you move forward, http://devdocs.io/ is a great collection of a lot of different programming resources, all in one unified interface.