0

Why does this throw the error and what is the correct way of calling an outer (global scope) function from within a module class?

//models.js
export default class Model {
    log() {
        gLog();     //Uncaught ReferenceError: gLog is not defined
    }
}

//main.js
import Model from './models.js';
let m = new Model();
m.log();

function gLog() {
    console.log(1);
}
2
  • Why do you need to call a global function within the class method? Design-wise this is ugly. Have you thought about passing the function as a parameter to the class (constructor) instead? Commented May 7, 2021 at 18:38
  • The example code is a simplified version of what I have. There are a number of similar modules which get data from websockets and feed it into a common function for aggregation. Commented May 7, 2021 at 19:51

1 Answer 1

1

A module does not have access to the objects declared in another module unless that module exports these objects. You should either include gLog in your models module (the easier way) or export it in your main.js then import main.js in models.

Sign up to request clarification or add additional context in comments.

2 Comments

The former won't work for me, because the global function needs to be called from several modules. Won't the latter solution cause some cross-reference error?
Do you mean circular references? No it won't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.