GideonKain
GideonKain

Reputation: 744

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>

Upvotes: 1

Views: 212

Answers (3)

benastan
benastan

Reputation: 2278

You need to surround the code in the body with a <script> tag.

Upvotes: 0

plalx
plalx

Reputation: 43718

Your JavaScript code is not in a script tag.

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

Upvotes: 0

zavg
zavg

Reputation: 11061

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>

Upvotes: 1

Related Questions