Tetragrammaton
Tetragrammaton

Reputation: 166

How would I access my constructor member in my class from an external function?

So, I am still a fresh man in JS. But I tried working around with my first bigger project. However, I just can't figure out why I can't access constructor members from functions that are outside of my main class. I assumed it had something to do with module.exports / require. So, that's how I did. Still, no luck.

Here is my code from the main.js file:

const funcs = require('./funcs.js');

class MainClass {
    constructor(omegga, config, store) {
        this.omegga = omegga;
        this.config = config;
        this.store = store;
    }
 async init() { 

    TestVehicle.on('cmd:test', async name => {
        const dss = await this.store.get('cats'); // this works fine.
        funcs.setSomething('29'); // this errors
        console.log(dss);
    });
  }
}
module.exports = MainClass;

async stop() { }

My function funcs.setSomething('29') errors however. Here's the function from funcs.js:

var MainClass = require('./main.js');
const teampo = new MainClass();

async function setSomething(argument1) {
    try {
        teampo.store.set('cats', argument1); // this errors
    } catch(e) { console.error(e); }
}
module.exports = { setSomething };

Now, JS tells me that something seems to be undefined. This is the error message I get:

"TypeError: Cannot read property 'set' of undefined"

I wonder why it is undefined? Shouldn't I be able to inherit store and all of its properties/methods? I've tried everything already, like changing require, the module.exports, etc. But it doesn't seem to work. Might the cause be more severe or is this some simple mistake I do and just have been overseeing the whole time?

Upvotes: 0

Views: 47

Answers (2)

T J
T J

Reputation: 43156

When you are creating the instance of the class here: const teampo = new MainClass();, you're not passing it the 3 things it requires which is

constructor(omegga, config, store) {}.

Since you didn't pass it a store, this.store, and thereby teampo.store is undefined

Upvotes: 2

ray
ray

Reputation: 27265

When you instantiate your class with const teampo = new MainClass(); you’re not passing any arguments. The constructor sets store to one of the arguments (this.store = store). Since there’s no store argument, this.store is undefined.

So if you subsequently attempt to call set on it it errors.

Upvotes: 2

Related Questions