Last active
August 29, 2015 14:27
-
-
Save himynameisdave/0729fa9376dcd9235d05 to your computer and use it in GitHub Desktop.
.bind(this) For Dummies [BROKEN]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //[BROKEN] | |
| var IceCream = { | |
| flavors: [ 'vanilla', 'chocolate', 'bubblegum' ], | |
| newFlavor: 'banana', | |
| addNewFlavor: function( ){ | |
| var safeToAdd = true; | |
| // check if we've added it already | |
| this.flavors.forEach(function(flavor){ | |
| if(flavor === this.newFlavor) // <- this throws an error | |
| safeToAdd = false; | |
| }); | |
| if(safeToAdd) | |
| this.flavors.push(this.newFlavor); | |
| } | |
| } | |
| IceCream.addNewFlavor(); |
Author
@ericperez Yes, there was a lot of better options I overlooked as I was trying to keep the article just about the .bind() method. I am in the process of editing it so that the whole array part isn't even in there.
I appreciate the feedback!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is there any reason that you keep the ‘newFlavor’ as a property of the IceCream object instead of just passing it in as an argument to the ‘addNewFlavor’ method? Also, have you considered using Array.prototype.filter() to ensure unique values in your array? It takes less code and makes it so you don’t have to keep track of the ‘safeToAdd’ state. e.g.:
Example Fiddle
NOTE: this will not work in IE versions < 8.
Cheers.