1

In the following example I don't clearly understand why this.add is not defined. I suspect that it is because the arrows function are executed immediately and at the moment of compilation and the add function does not yet exist. Is this assumption correct? Or I'm missing something.

const arr= [1, 2, 3]
const squares = {  
  num: (arr) => {
    return arr.map((x) => {
      return (x * x) + this.add()
    })
  },
  add: () => {
    return 1
  }
}
//TypeError: this.add is not a function
console.log(squares.num(arr)) 
James
  • 587
  • 1
  • 7
  • 21

1 Answers1

1

You're using lexical this all the way out of the object. You'll need to avoid using an arrow function for num:

See documentation for arrow functions:

"An arrow function expression has a shorter syntax than a function expression and does not bind its own this..."

const arr = [1, 2, 3]
const squares = {
  num: function(arr) {
    return arr.map((x) => {
      return (x * x) + this.add()
    })
  },
  add: () => {
    return 1
  }
}
console.log(squares.num(arr))
KevBot
  • 17,900
  • 5
  • 50
  • 68
  • The lexical scoping of “this” in the previous example means that is only available inside the arrow function `{ }`? – James Jul 19 '17 at 16:11
  • @James: It means that `this` inside the arrow function refers to whatever `this` refers to in the scope where `squares` and `arr` are defined... it works exactly like you would expect any other variable to work. – Felix Kling Jul 19 '17 at 16:26
  • The following notes from the MDN documentation were key to understand: 1). Arrow functions used as methods: As stated previously, arrow function expressions are best suited for non-method functions. 2). An arrow function does not create its own this, the this value of the enclosing execution context is used. – James Jul 19 '17 at 16:50
  • 1
    @James, I apologize for responding so late, I was needed away from my computer. I'm glad that you were able to get this figured and found other documentation that explained how it works. – KevBot Jul 19 '17 at 17:37