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.

  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.

  var Cat = Class.create();
  Cat.prototype = {
    initialize: function(name) {
      this.name = name;
    }
  };

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.

  var Cat = Class.create();
  Cat.prototype = {
    initialize: function(name) {
      this.name = name;
    },
    meow: function() {
      alert(this.name + " : meow!");
    }
  };

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.

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

Comments

comments powered by Disqus