简体   繁体   中英

How to call an outer scope function from within a JS module class

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);
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM