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().
var Person = Class.create({ name : null, initialize : function(name) { this.setName(name); }, setName : function(name) { this.name = name; }, getName : function() { return this.name; } });
<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>


