PhpRiot
Download Article
Download this article or the entire “Eight Weeks of Prototype” series with all listings and files.




More information
Related Books
JavaScript: The Good Parts

JavaScript: The Good Parts

Most programming languages contain good and bad parts, but JavaScript has more than its share...

jQuery: Novice to Ninja

jQuery: Novice to Ninja

jQuery: Novice to Ninja is a compilation of best-practice jQuery solutions to meet the most...
PhpRiot Newsletter
Your Email Address:

More information

Eight Weeks of Prototype: Week 6, Writing JavaScript Classes with Prototype

Defining the Class Constructor

In Object-Oriented Programming, the class constructor is a method that is executed when the class is instantiated. By default JavaScript doesn't use constructors when you create classes, but Prototype allows us to do so by creating a function called initialize().

When you create a new instance of your class the initialize() function will be executed. You can pass arguments to the constructor by including them when you instantiate the class.

To demonstrate this, I'll now modify the Person class so rather than having to set the name by calling setName() after you create a Person object, you can set the name in the constructor.

Listing 4 shows the new version of the Person.js file, while Listing 5 shows how you can now instantiate the class and set the name without explicitly calling setName().

Listing 4 The Person class with a constructor which sets the name (Person.js)
var Person = Class.create({
 
    name : null,
 
    initialize : function(name)
    {
        this.setName(name);
    },
 
    setName : function(name)
    {
        this.name = name;
    },
 
    getName : function()
    {
        return this.name;
    }
});
Listing 5 Defining the person's name when instantiating the Person class (listing-5.html)
<html>
    <head>
        <title>Loading and instantiating the Person class</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
        <script type="text/javascript" src="/js/Person.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            var me = new Person('Quentin Zervaas');
 
            alert(me.getName());
        </script>
    </body>
</html>

In This Article