0

I am not sure if JS modules are supposed to work like this, but it doesn't make sense. I am using React and I would like to export an object from one module and then call methods on that object. This work well so far, however, the issue is that inside the invoked method, this doesn't point to the object on which it was invoked, and I can't access other member methods. Here is an example:

export let localService = {
     getData: () => {
        console.log(this);
        this.testMethod();
     },

    testMethod: () => {

    }
};

In the other file I import the object and invoke the method:

import {localService} from '../../localService.js';

localService.getData();

Now things get strange, inside the getData I can't access this.testMethod() directly because this is sort of different, here's the output of console.log(this)

enter image description here

and of course invoking this.testMethod() throws an error saying that method doesn't exist. I am able to access testMethod() like this: this.a.testMethod() , but where does this a come from? So is this normal behavior, or maybe it's React's fault ?

Zed
  • 4,821
  • 6
  • 34
  • 71
  • 2
    Review how arrow functions affect `this`: [Value of this inside arrow function inside an Object](https://stackoverflow.com/q/44080949). The `a` is likely a byproduct of whatever packaging software you're using (likely Webpack if you're using React's default). – Heretic Monkey Sep 18 '18 at 12:12
  • 1
    could you please post complete code ? – Amruth L S Sep 18 '18 at 12:15
  • @Isa42999 that's the complete code. Heretic you're correct, without arrow functions it work's as expected, thanks!. – Zed Sep 18 '18 at 12:18
  • what you want to achieve here ? calling `localService.getData();` should trigger `testMethod` ? – Amruth L S Sep 18 '18 at 12:49

1 Answers1

0

now your localService is type of json data that's the reason you are getting a when you console, you can't call other functions there.

you have to create each functions individually.

create localService.js with below content.

export const getData = () => {
    console.log("getData");
    testMethod();
};

export const testMethod = () => {
    console.log("testMethod");
};

import localService.js like this.

import * as localService from '../../localService.js';

now you can call localService.getData()

Amruth L S
  • 4,439
  • 1
  • 21
  • 38