简体   繁体   English

如何从 JS 模块 class 中调用外部 scope function

[英]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?为什么这会引发错误,从模块 class 中调用外部(全局范围)function 的正确方法是什么?

//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 .您应该在您的models模块中包含gLog (更简单的方法)或将其导出到您的main.js中,然后在models中导入main.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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