javascript - ES6 - Rebinding class methods -


i'm experimenting es6 classes , i've come across issue don't understand. want make class initialized giving function. class has method runs function, given context. i've attempted this:

class myclass {   constructor(action) {     this.action = action;   }   run(context, n) {     this.action.call(context, n);   } }  // instantiate class function uses 'this' log given number let = new myclass((n) => {   this.log(n); })  // calls run method of class, giving console context , 1 n. a.run(console, 1); 

i expect code result in 1 being logged console. however, i'm instead getting typeerror.

i assume misunderstanding how classes , context-binding work in es6. can me out?

edit

well lesson on difference between arrow functions , function declarations. answers!

your use of arrow functions breaking things

let = new myclass((n) => {   this.log(n); }); 

is same as

let _this = this; let = new myclass(function(n) {   _this.log(n); }); 

because arrow functions scope parent. should use normal function as

let = new myclass(function(n) {   this.log(n); }); 

Comments