user2952238
user2952238

Reputation: 787

Import class fails with ES6 syntax

I'm trying with this syntax to import and init a class in ES6. But the console says 'undefined property hej'.

Work.js

class Work {

    constructor() {

    }

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

export default Work;

Main.js

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


Work.hej();

Whats causing this error? How to solve it?

Upvotes: -1

Views: 78

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074138

Your Work function has no hej property. hej is a property of the prototype that new Work would assign to an instance, so:

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

Or if you want to use it as Work.hej();, make it 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).


If you use this plunkr on the most recent version of Chrome, it'll show that it's working (with an instance method). Here's the source:

index.html:

<!DOCTYPE html>
<html>

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

</html>

work.js:

class Work {
    constructor() {
    }

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

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). Here's the source:

index.html (same as above)

work.js:

class Work {
    constructor() {
    }

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

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).

Upvotes: 3

Related Questions