Search code examples
javascriptthisprototype

Object prototype can't access properties with `this`


So, I saw several examples that this should work. But obviously, I'm missing something, because it doesn't. :/

Could somebody please explain to me what I'm doing wrong here? :)

function Code (b) {
  this.b = b
  this.arr = []
}

Code.prototype.add = (v) => {
  console.log(this.b)
  this.arr.forEach(element => {
    console.log(element)
  });
  this.arr.push(v)
}

var c = new Code('bla')
console.log(c.add('asdf'))

So this throws an error with:

this.arr.forEach(element => {
  ^

TypeError: Cannot read property 'forEach' of undefined

Obviously, I'm doing something wrong here. But I don't know what.

Thanks! Gergely.


Solution

  • function Code (b) {
      this.b = b
      this.arr = []
    }
    Code.prototype.add =function(v){
      console.log(this.b)
      this.arr.forEach(function(element){
        console.log(element)
      });
      this.arr.push(v)
      console.log(this.arr)
    }
    
    var c = new Code('bla')
    console.log(c.add('asdf'))
    

    You should use function(), instaed of () => arrow fucntion, since arrow function's this works differently.
    this of an arrow function only refers to this that exists in the outer scope.