最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to use a external Javascript class in html? - Stack Overflow

programmeradmin3浏览0评论

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

ponent.js:

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

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

main.html:

<html>
<script src="./ponent.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?

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

ponent.js:

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

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

main.html:

<html>
<script src="./ponent.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?

Share Improve this question asked Apr 1, 2018 at 7:13 mkusemkuse 2,5085 gold badges38 silver badges66 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

after test i think the problem is your format

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

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

</head>

<body>

</body>

</html>

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

Please try by

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

TryClass.prototype.sayHi = function () {
    alert( this.name );
}
发布评论

评论列表(0)

  1. 暂无评论