Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Add Properties to Objects in Your HTML5 Game

One of the most interesting things about HTML game objects is that they are variables that can contain other variables. When a variable exists in the context of an object, the variable is called a property. Properties are the characteristics of an object, such as its speed or its size. As an example, please look at the following variation of the critter code:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
 <meta charset="UTF-8">
 <title>critterSpeed.html</title>
 <script type="text/javascript"
   src = "simpleGame.js">
 </script>
 <script type="text/javascript">
  var game;
  var critter;
 
  function Critter(){
   tCritter = new Sprite(game, "critter.gif", 30, 30);
   tCritter.speed = 3;
   tCritter.setSpeed(tCritter.speed);
   return tCritter;
  }
 
  function init(){
   game = new Scene();
   critter = new Critter();
   game.start();
  }
 
  function update(){
   game.clear();
   critter.update();
  }
 </script>
</head>
<body onload = "init()">
</body>
</html>

A property is simply a special variable associated with an object. Normally, you use object.property to designate that a particular property is associated with a particular object. For this example, here is how you add a speed property to the Critter object.

  1. Build a property by referring to it.

    In JavaScript, you can simply refer to a variable, and it will be created. This is also true in objects. Simply make a reference to Critter.speed, and the Critter object magically has a speed property.

  2. Create properties in the constructor.

    You can technically create or refer to a property anywhere, but normally they're created in the constructor.

  3. Use the property like any other variable.

    The property acts like any other variable, so you can use it to actually change the speed of the object.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.