O'Reilly logo

Building HTML5 Games with ImpactJS by Jesse Freeman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How Classes Work

In JavaScript, there is no real notion of a traditional class structure like you have in other OOP languages. In JavaScript, everything is an Object. While this allows JavaScript to be incredibly flexible, it also makes it difficult to structure your code in a reusable way. To solve this issue, Impact has a pseudo-class object, which is the basis of every class we will create in our game.

Note

Impact’s class object is based on John Resig’s simple JavaScript inheritance code (http://ejohn.org/blog/simple-javascript-inheritance), but it is extended with deep copying of properties and static instantiation.

Here is an example of how we can create a new person class by building off of Impact’s core Class object:

1    // Create a new class "Person"
2    var Person = ig.Class.extend({
3        name: '',
4        init: function( name ) {
5            this.name = name;
6        }
7    });
8
9    // Instantiate an object of the first class
10    var e = new Person('John Doe');
11    e.name; // => John Doe

You may have noticed that we actually extend the functionality of the ig.Class object via the .extend() method.

Note

In traditionally class based languages, the extends keyword allows us to copy over the existing functionality of another class. This is what will allow us to infuse additional functionality into all of our game classes without having to actually duplicate code all over the place.

In addition to extending off of ig.Class, you can actually extend off of any custom class you create. Again, in order to extend another class you simply use the .extend() functionality. Here we are going to extend off of our person class to create a new zombie class:

1    // Create another class by extending the "Person" class
2    var Zombie = Person.extend({
3        init: function( name ) {
4            this.parent( 'Zombie: ' + name );
5        }
6    });
7
8    // Instantiate an object of the second class
9    var p = new Zombie('John Doe');
10    p.name; // => Zombie: John Doe

All classes that are created with .extend() will also have an .extend() method that can be used for further subclassing. When working inside of extended classes, you can use .this and .parent for scope. You will see later on how splitting up core logic into individual classes will help expostulate functionality and make our game code easier to maintain while we develop it.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required