6

I have a .js file which has a class defined. I want to call this class from <script> from another html file.

component.js:

class TryClass {
  constructor(name) {
    this.name = name;
  }

  sayHi() {
    alert( this.name );
  }
}

main.html:

<html>
<script src="./component.js" />

<script>
var user = new TryClass( "John" );
user.sayHi();
</script>

<body>
</body>

This doesn't show the alert when I load main.html (from my webserver). However, with the inspect console, I am able to use the TryClass.

How to resolve this?

2 Answers 2

7

after test i think the problem is your format

<!DOCTYPE html>
<html lang="en">

<head>
    <script src="component.js"></script>
    <script>
        var user = new TryClass("John");
        user.sayHi();
    </script>

</head>

<body>

</body>

</html>

you lost</script> after <script src="./component.js" />,i guess this is the worst error though you also lost </html> and <head></head>

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

Comments

-1

Please try by

var TryClass = function(name){
    this.name = name;
}

TryClass.prototype.sayHi = function () {
    alert( this.name );
}

1 Comment

This doesn't really answer the question. Your answer is in ES5 format and the author's post is in ES6 for describing a class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.