代码之家  ›  专栏  ›  技术社区  ›  helpME1986

从浏览器控制台JS调用类(在模块中定义)时,“Uncaught ReferenceError:…未定义”

  •  2
  • helpME1986  · 技术社区  · 8 年前

                //implementation details
                const _stackCollection = new WeakMap();
    
    
                //interface
                export class Stack {
    
                    constructor() {
                        _stackCollection.set(this, []);
                    }
    
                    get count() {
                        return _stackCollection.get(this).length;
                    }
    
                    pop() {
                        if (this.count === 0)
                            throw new Error('Nothing to pop');
    
                        return _stackCollection.get(this).pop();
                    }
    
                    peek() {
                        if (this.count === 0)
                            throw new Error('Nothing to peek');
    
                        return _stackCollection.get(this)[this.count - 1];
                    }
    
                    push(e) {
                        _stackCollection.get(this).push(e);
                        return;
                    }
    
                }
    

    导入给定类的模块如下所示 模块.js:

       import {Stack} from './class.js';
    

    index.html如下所示:

        <!DOCTYPE html>
        <html lang="en">
    
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <title>Document</title>
        </head>
    
        <body>
    
            <h1>hello world</h1>
    
    
        <script type="module" src='module.js'></script>
    
    
        </body>
        </html>
    

    当我尝试在控制台中初始化Stack的实例时,会得到以下错误。关于给定的错误有很多问题,但我看不出有什么可以帮助我:

        const stack=new Stack()
    
        Uncaught ReferenceError: Stack is not defined
        at <anonymous>:1:13
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   Aluan Haddad Vikrant Kashyap    8 年前

    模块中的声明的作用域是该模块。如果要访问它们,则需要导入它们。

    要在浏览器控制台中使用这种导出,需要将其导入或绑定到全局变量。

    全局(请注意,这违背了模块的目的,只应用于特殊测试)

    export class A {}
    
    // TODO: remove this
    window.A = A;
    

    // browser console:
      import('./a.js').then(console.log);
    

    使用SystemJS

    // browser console:
    SystemJS.import('./a.js').then(console.log);
    
        2
  •  0
  •   helpME1986    8 年前

    谢谢大家的评论。正如@AluanHaddad在一条注释中提到的,我无法从控制台初始化对象类,因为我尝试了:

       const stack=new Stack()
    

     import {Stack} from './class.js';
    
     const c = new Stack();
     c.push('a');
    
     window.c = c;
    

    然后我可以从控制台访问对象c

        >c
        >Stack {}