Edits: I’d like to thank everyone for their feedback, it’s been rad! :) I learned a whole bunch and have made a few small edits to reflect this. The concepts discussed here are still the same though.
Let me give you an example of one of the silliest things that I was doing, all because I didn’t know there was a better way to do it. All the facepalms.
I’ve been writing a lot of module-based stuff (and eating a lot of ice cream) lately, and so it’s common that I’ll have an object like this:
Okay so this is a little `IceCream` object that has a list of flavors, as well as a new flavor to be added. We call the `addNewFlavor()` method and it loops through the existing flavors to make sure the new one doesn’t already exist in our list, using forEach.
The code above may not throw an error, but if we were to log the value of this.newFlavor right before that if statement in the forEach, it would return undefined. This is because of scoping — the anonymous function being passed to forEach has it’s own separate “this” scope separate from the IceCream object’s “this” scope.
So like a jackass riding into battle without a horse, I re-wrote the “addNewFlavor” method to look something like this:
I’m essentially referencing “this” with a new variable, “context”, that is available from within the function we pass to forEach, which just sorta feels weird. Don’t worry though, there is a much nicer and cleaner way to do this, and it is by using the .bind() method.
Quickly, before I get into it, I’d like to make two quick points I learned after initially publishing this. First is that forEach accepts a second parameter that essentially does what we’re trying to do. Awesome, thanks for the tips guys. Second is that arrow functions in ES6 solves this for us :)
Okay so back to .bind(). It essentially (not true, but close enough) calls the function using whatever you provide to it as your “this” context. Lets see it in the wild:
Did you catch that? All we did was append `.bind(this)` to our expression and boom, everything runs as you’d expect. What .bind() is doing is essentially saying “this anonymous function will be called and the outer ‘this’ will be bound to the inner ‘this’,” which means that if you refer to ‘this’ inside of that anonymous forEach function you’ll actually be refering to the outer object. “this” is a really neat concept.