如何将JavaScript对象包含在单独的文件中

时间:2013-05-14 00:40:27

标签: javascript html5 oop object

我正在尝试包含一个单独的.js文件,因此我可以引入一个我创建的类但它不起作用,有人可以告诉我为什么吗?

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>

3 个答案:

答案 0 :(得分:1)

您忘记将JS代码包装到<script>标记

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

答案 1 :(得分:0)

您的JavaScript代码不在script标记中。

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

答案 2 :(得分:0)

您需要使用<script>标记围绕正文中的代码。