How to Add Properties to Objects in Your HTML5 Game - dummies

How to Add Properties to Objects in Your HTML5 Game

By Andy Harris

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:

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

A property is simply a special variable associated with an object. Normally, you use 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.