简体   繁体   English

导入类使用ES6语法失败

[英]Import class fails with ES6 syntax

I'm trying with this syntax to import and init a class in ES6. 我正在尝试使用这种语法来导入和初始化ES6中的类。 But the console says 'undefined property hej'. 但是控制台显示“ undefined property hej”。

Work.js Work.js

class Work {

    constructor() {

    }

    hej() {
        alert('hej');
    }
}

export default Work;

Main.js Main.js

import Work from './modules/work.js';


Work.hej();

Whats causing this error? 是什么导致此错误? How to solve it? 怎么解决呢?

Your Work function has no hej property. 您的Work功能没有hej属性。 hej is a property of the prototype that new Work would assign to an instance, so: hejnew Work将分配给实例的原型的属性,因此:

const w = new Work();
w.hej();

Or if you want to use it as Work.hej(); 或者如果您将其用作Work.hej(); , make it static : ,使其static

class Work {
    static hej() {
//  ^^^^^^-----------------
        alert("hej");
    }
}

Then Work.hej() works, because hej is a static method (a method of Work , not of instances of Work ). 然后Work.hej()起作用了,因为hej是一个静态方法( Work方法,而不是Work 实例的方法)。


If you use this plunkr on the most recent version of Chrome, it'll show that it's working (with an instance method). 如果您在最新版本的Chrome上使用此plunkr ,它将显示它正在运行(使用实例方法)。 Here's the source: 来源:

index.html : index.html

<!DOCTYPE html>
<html>

  <body>
    <script type="module" src="work.js"></script>
    <script type="module" src="main.js"></script>
  </body>

</html>

work.js : work.js

class Work {
    constructor() {
    }

    hej() {
        document.body.appendChild(
          document.createTextNode("hej")
        );
    }
}
export default Work;

main.js : main.js

import Work from './work.js';

const w = new Work();
w.hej();

If you use this one on the most recent version of Chrome, it'll show that it's working (with a static method). 如果您在最新版本的Chrome上使用版本,则会显示它正在运行(使用静态方法)。 Here's the source: 来源:

index.html (same as above) index.html (与上面相同)

work.js : work.js

class Work {
    constructor() {
    }

    static hej() {
        document.body.appendChild(
          document.createTextNode("hej")
        );
    }
}
export default Work;

main.js : main.js

import Work from './work.js';

Work.hej();

Note that module support in Chrome is really new , you do need to be completely up-to-date (as I write this, late October 2017). 请注意,Chrome中的模块支持确实是新的 ,您需要完全最新(正如我在2017年10月下旬所写)。

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

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