ShiftEleven

How to Create Objects in Object-Oriented JavaScript with Prototype

Javascript Kata has a teriffic article on how to create objects with JavaScript the old fashion way, without any JavaScript libraries. But I use prototype and it has its very own way to create a classes.

Creating an empty class

In keeping with the cat theme of Javascript Kata, I will create my own Cat class. This is very easy to do; you simply create a new class and assign it to a variable.

1  var Cat = Class.create();

Creating the constructor

Unlike the Javascript Kata example, the constructor is not set inside of the function which created the class. Instead it is put into the prototype attribute of the class, under the special method name initialize.

1  var Cat = Class.create();
2  Cat.prototype = {
3    initialize: function(name) {
4      this.name = name;
5    }
6  };

Adding a instance method

To add an instance method to our Cat class, all one has to do is add another property to the prototype definition.

1  var Cat = Class.create();
2  Cat.prototype = {
3    initialize: function(name) {
4      this.name = name;
5    },
6    meow: function() {
7      alert(this.name + " : meow!");
8    }
9  };

What I like about this is it keeps all references to this in one spot.

Making the cat meow

The way that the code is constructed is different; however, the way to instantiate our Cat class is exactly the same as it would be if you didn't use prototype.

1  var mistigri = new Cat('Mistigri');
2  mistigri.meow();

Comments

comments powered by Disqus