PhpRiot
Follow phpriot on Twitter
Sponsored Link
Download Article
Download this article or the entire “Eight Weeks of Prototype” series with all listings and files.




More information
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store
Free iPad/iPhone App
Available on the App Store

  • PHP manual
  • Zend Framework manual
  • Smarty manual
  • PHP articles
  • PHP training

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...

Learning PHP, MySQL, and JavaScript: A Step-By-Step Guide to Creating Dynamic Websites (Animal Guide)

Learning PHP, MySQL, and JavaScript: A Step-By-Step Guide to Creating Dynamic Websites (Animal Guide)

If you know HTML, this guide will have you building interactive websites quickly. You'll learn...

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