I'm currently experimenting with ES6 classes and I've come across this issue that I don't fully understand. I want to make a class which is initialized by giving it a function. The class has a method that runs the function, but with any given context. I've attempted to do so with something like this:
class MyClass {
constructor(action) {
this.action = action;
}
run(context, n) {
this.action.call(context, n);
}
}
// instantiate my class with a function that uses 'this' to log a given number
let a = new MyClass((n) => {
this.log(n);
})
// calls the run method of my class, giving console as the context and 1 as n.
a.run(console, 1);
I would expect this code to result in 1 being logged to the console. However, I'm instead getting a TypeError.
I assume I am misunderstanding something about how classes and context-binding work in ES6. Can anyone help me out?
Edit
Well this was a good lesson on the difference between arrow functions and function declarations. Thanks for the answers!