ga-wdi-boston / js-function-context-this

Other
0 stars 126 forks source link

Replace this example / add more explanation #26

Closed raq929 closed 7 years ago

raq929 commented 8 years ago

This (haha) example uses this in two different ways, and is therefore confusing to beginners.

function Counter() {
  this.sum = 0;
  this.count = 0;
}
Counter.prototype.add = function(array) {
  array.forEach(function(entry) {
    this.sum += entry;
    ++this.count;
    console.log(this);
  }, this);
  // ^---- Note
};

let obj = new Counter();
obj.add([2, 5, 9]);
obj.count
// 3
obj.sum
// 16
gaand commented 8 years ago

I'm not sure what you mean by "in two different ways". The array iteration methods take an argument to set the value of this for the callback. How it's being used here seems like a pattern to me.

payne-chris-r commented 8 years ago

@rts make sure you take a look at 014/master. I pushed some code just recently that I think makes this example a little less confusing.