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

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

Creating a String Representation of Your Class

If you want to define a string representation of an instance of your class, you can do so by defining a class method called toString(). This method must return a string.

Effectively what this does is define what value should be returned when your object is converted (cast) to a string. Listing 16 shows an example of how you might choose to implement toString(). Listing 17 shows how the object is displayed when converted to a string.

Listing 16 Declaring the toString() method (Person.js)
var Person = Class.create({
    name : null,
    initialize : function(name)
    toString : function()
        return this.getName();
    setName : function(name)
    { = name;
    getName : function()
    getCountry : function()
        return 'Unknown';
Listing 17 Converting an object to a string so it can be displayed (listing-17.html)
        <script type="text/javascript" src="/js/prototype.js"></script>
        <script type="text/javascript" src="/js/Person.js"></script>
        <div id="foo"></div>
        <script type="text/javascript">
            var me = new Person('Quentin Zervaas');

When you view this listing in your browser, the instance of Person will be converted to a string so it can populate the #foo div. If you are creative you could do some other magic, such as returning HTML code to output a photo of the person. For instance, toString : function() { return '<img src="..." />'; }.

In This Article