0

I am learning ES6 at the moment. Just figured out a little bit about classes. Right now I have a collection of helpers in a JSON object. How do I refer to itself? I use babel to convert it to ES5 and it doesn't like it, it makes "_this" out of "this".

const pixieLib = {
  methodA : (arg1) => {
    console.log('foo');
  },

  methodB : () => {
    this.methodA();
  }
};

If there are better ways to make helpers all suggestions are welcome when they play nice with Babel.

poashoas
  • 1,790
  • 2
  • 21
  • 44
  • I don't see what this has to do with `class`es. Also I think your issue is unrelated to Babel, the code just doesn't work, even when executed natively. – Bergi Jun 05 '21 at 19:47

1 Answers1

2

You've used an arrow function, which by definition closes over the this where it's created.

If you don't use, it will work normally:

const pixieLib = {
  methodA : function(arg1) {
    console.log('foo');
  },

  methodB : function()  {
    this.methodA();
  }
};

Babel REPL test

Edit:

or use ES6 Method Definitions syntax as pointed by @trincot.

const pixieLib = {
  methodA(arg1) {
    console.log('foo');
  },

  methodB()  {
    this.methodA();
  }
};

REPL Result