简体   繁体   中英

How to include a JavaScript object in a separate file

I'm trying to include a separate .js file so I can pull in a class I created but it doesn't work, can someone tell me why?

playercharacter.js

function PlayerCharacter() {
this.x = 0; 
this.y = 0;

this.dx = 5;
this.dy = 5;
}


PlayerCharacter.prototype.sayHello = function()
{
 alert ('hello');
};

index.html

<html>
<head>
<script src="js/playercharacter.js" type="text/javascript" ></script>
</head>
<body>
 <script type="text/javascript" >
var player = new PlayerCharacter();
player.sayHello();
</script>
</body>
</html>

You forgot wrap your JS-code into the <script> tags

<html>
 <head>
  <script src="js/playercharacter.js" type="text/javascript" ></script>
 </head>
 <body>
  <script type="text/javascript" >
   var player = new PlayerCharacter();
   player.sayHello();
  </script>
 </body>
</html>

Your JavaScript code is not in a script tag.

<script>
    var player = new PlayerCharacter();
    player.sayHello();
</script>

您需要使用<script>标记将代码包含在主体中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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