javascript - This not working as expected in nested arrow functions in ES6 -


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.

fiddle


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -