Javascript Kata has a teriffic an 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();
Published in JavaScript
Tags: ,

4 Responses to “How to Create Objects in Object-Oriented JavaScript with Prototype”

  1. May 1st, 2007 at 8:01 am #Dan of javascript kata

    Hi Adam,
    I didn’t know that prototype had a helper for class creation. I guess you can also make some inheritance…

    Maybe you are wondering why I use a Cat as example. First, I really like cats. Second, it is not a reusable class that you can copy/paste in your project. That way, the reader that wants to do a class has to understand the technic and he is not just using the class blindly.

    Thanks for you post!

  2. May 1st, 2007 at 9:37 am #Andrew Sazonov

    Here is a link to an article which compares various techniques to implement inheritance in JavaScript (and their benefits and drawbacks) and also includes points why prototype.js is not perfect:

    http://www.soft-amis.org/jsiner/inheritance.html

  3. May 7th, 2007 at 10:46 am #Troy

    It doesn’t work for me. I’ve tried it in IE6, Opera9 – no errors, just nothing happens.

  4. May 8th, 2007 at 6:52 am #K. Adam Christensen

    It works for me. Are you including the “prototype framework”:http://www.prototypejs.org/ with this code?

Leave a Reply