javascript - This not working as expected in nested arrow functions in ES6 -
this question has answer here:
i'm new arrow functions , don't understand why can use code:
const adder = { sum: 0, add(numbers) { numbers.foreach(n => { this.sum += n; }); } }; adder.add([1,2,3]); // adder.sum === 6 ... , works fine, in following case this not bound properly:
const adder = { sum: 0, add: (numbers) => { numbers.foreach(n => { this.sum += n; }); } }; adder.add([1,2,3]); // cannot read property sum
from mdn:
an arrow function expression has shorter syntax function expression , not bind own this, arguments, super, or new.target.(...)
meaning inside arrow function this refers outter this there is. if run in browser, this window object.
use adder.sum instead of this.sum.
Comments
Post a Comment