-1

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

I see, thanks. What if i want hej to be a method? As my intention is.
@user2952238: I just realized I should have considered that option and was editing; hit refresh. :-)
hm, then i get this: _work2.default is not a constructor
@user2952238: Then something isn't as you've shown it. With what you've shown, and only the changes above (one or the other), both things work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.