Skip to content

Instantly share code, notes, and snippets.

@himynameisdave
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save himynameisdave/0729fa9376dcd9235d05 to your computer and use it in GitHub Desktop.

Select an option

Save himynameisdave/0729fa9376dcd9235d05 to your computer and use it in GitHub Desktop.
.bind(this) For Dummies [BROKEN]
//[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();
@ericperez
Copy link

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.:

var IceCream = {
  flavors: ['vanilla', 'chocolate', 'bubblegum', 'spinach'],
  addNewFlavor: function(new_flavor) {
    this.flavors.push(new_flavor);
    this.flavors = this.flavors.filter(function(elem, index, arr){
      return arr.indexOf(elem) >= index;
    })
  }
};

console.log(IceCream.flavors);
IceCream.addNewFlavor('banana');
console.log(IceCream.flavors);
IceCream.addNewFlavor('spinach');
console.log(IceCream.flavors);

Example Fiddle

NOTE: this will not work in IE versions < 8.

Cheers.

@himynameisdave
Copy link
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