How to create a class using prototype.js

javascript, oop, prototypejs

Solution

Creating PrototypeJS Classes is very similar to creating classes in normal OOP languages.

First start off by naming your class

var myClass = Class.create({ });

This will create an empty class - now populate it with methods, if you put a method `initialize` PrototypeJS will fire that as the constructor

var myClass = Class.create(
{
    initialize : function()
    {
        this.options = 0;
    }
});

You can setup anything you want in the `initialize()` method like default values or just initializing the properties of the class. Lets put in some other methods and show how to instantiate the class.

var myClass = Class.create(
{
    initialize : function()
    {
        this.options = 0;
    },

    testme : function()
    {
        this.options++;
    },

    showme : function()
    {
        alert(this.options);
        return this.options;
    }
});

var theClass = new myClass();

Lets take it one more step and call other methods within methods and pass options to the constructor.

var myClass = Class.create(
{
    initialize : function(option)
    {
        this.options = (option ? option : 0);

        this.testme();
    },

    testme : function()
    {
        this.options++;
    },

    showme : function()
    {
        alert(this.options);
        return this.options;
    }
});

var theClass = new myClass(200);
theClass.showme();

//will alert 201 and return 201

This is cool and all - but what about class inheritance? That is a big thing in OOP - lets say we have a separate class that is a child class of `myClass`. For any method that you are overriding in the child class you can pass a first variable as `$super` and that will refer to the parent's method of the same name - similar to a scope resolution

var myChildClass = Class.create(myClass,
{
    initialize : function($super,option)
    {
        $super(option);

        // the child class needs option's default value at 150 or whatever is 
        // passed so run the parent initialize first and then redefine the 
        // option property
        this.option = (option ? option : 150);

        // you can still run methods in the parent that are not overridden in 
        // the child
        this.testme();
    }
});

var child = new myChildClass();
child.showme();

//will alert() 151 and return 151

I hope this is helpful for you.

Here are some more complex real world examples from my github

https://github.com/jwestbrook/Prototype.Growler

https://github.com/jwestbrook/Prototype.Watermark

https://github.com/jwestbrook/bootstrap-prototype

Problem

Could any one shows an example for creating a class using prototype.js and how it works.Can anyone provide good examples and tutorials for prototype.js other than its official site?

Original source