PhpRiot
Download This 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 of...

Practical Prototype and script.aculo.us (Expert's Voice in Web Development)

Practical Prototype and script.aculo.us (Expert's Voice in Web Development)

As a JavaScript developer, you will already be aware of some of the time saving, convenience,...
Browse Articles
Ajax (4), APC (1), CAPTCHA (1), CSS (3), Debugging (1), File Upload (1), Google (3), Google Maps (2), JavaScript (12), JSON (2), MVC (1), MySQL (7), onbeforeunload (1), OOP (1), PHP (28), PhpDoc (1), PostgreSQL (6), Prototype (11), Reflection (1), RFC 1867 (1), Robots (1), Scriptaculous (1), SEO (1), Sessions (1), SimpleXML (1), Smarty (5), SOAP (1), SPL (1), Templates (2), W3C (1), XHTML (1), Zend Framework (1), Zend_Search_Lucene (1)

PhpRiot Newsletter
Your Email Address:

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)
    {
        this.setName(name);
    },
 
    toString : function()
    {
        return this.getName();
    },
 
    setName : function(name)
    {
        this.name = name;
    },
 
    getName : function()
    {
        return this.name;
    },
 
    getCountry : function()
    {
        return 'Unknown';
    }
});
Listing 17 Converting an object to a string so it can be displayed (listing-17.html)
<html>
    <head>
        <title></title>
        <script type="text/javascript" src="/js/prototype.js"></script>
        <script type="text/javascript" src="/js/Person.js"></script>
    </head>
    <body>
        <div id="foo"></div>
 
        <script type="text/javascript">
            var me = new Person('Quentin Zervaas');
            $('foo').update(me);
        </script>
    </body>
</html>

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


Tagged in ,