0

I want to separate a class implementation across different files, and I did it this way:

A.js:

export default class A {
   constructor() {
     this.a = 0;
   }
}

B.js

import A from ...

A.prototype.foo = (n) => { this.a = n; };

But the problem is that when I call foo, this is undefined.

Any idea on how to fix it?

Lucas
  • 171
  • 1
  • 11
  • 1
    You're using an `=>` function. Change it to a classic `function` function and it'll work. – Pointy Jan 14 '19 at 12:46
  • @Pointy why?.... – mplungjan Jan 14 '19 at 12:46
  • Because like this the context of definition of it is not the prototype object? – Dellirium Jan 14 '19 at 12:47
  • @mplungjan I'm looking for a dup but I have some sort of psychic block with finding them :/ – Pointy Jan 14 '19 at 12:49
  • https://stackoverflow.com/questions/24900875/whats-the-meaning-of-an-arrow-formed-from-equals-greater-than-in-javas – raina77ow Jan 14 '19 at 12:49
  • 1
    https://dmitripavlutin.com/when-not-to-use-arrow-functions-in-javascript/ – Andy Jan 14 '19 at 12:50
  • @luc4s you sure that `this` is undefined? rather then `a` being undefind? – Dellirium Jan 14 '19 at 12:50
  • Wow I didn't know about the difference between the two, thank you! (it worked) – Lucas Jan 14 '19 at 12:53
  • 2
    Biggest problem with arrow functions, is that a lot of newcomers to JS assume it's just a shorthand for `function()`, but it does more than this. It also binds `this` to the current `this`, during the OP's assignment `this` will be undefined. – Keith Jan 14 '19 at 13:05

0 Answers0