Quantcast
Channel: Anselm Bradford » JavaScript
Viewing all articles
Browse latest Browse all 4

Object-Oriented JavaScript Tip: Overriding toString() for readable object imprints

$
0
0

JavaScript has a core Object class that contains a toString() method that is called whenever a request is made to convert an object to a string (like related ECMAScript-based ActionScript). This is often done during debugging to check that a variable actually contains a reference to a certain object.

Most likely alert(myObj) or console.log(myObj) would be used, for example:

var myObj = new Object()
alert(myObj); // popup displays [object Object]

The problem is if you create a custom object. In this case it would be ideal to adjust the string representation to reflect the fact that the custom object is different from the core object. By default there is no difference, as the following example demonstrates:

// custom Foo class
function Foo() 
{	
}
 
// new Foo object instance
var f = new Foo();
alert(f);  // popup displays [object Object]

To make this more readable, add a toString() method to the prototype of the object:

function Foo() 
{
}
 
// toString override added to prototype of Foo class
Foo.prototype.toString = function()
{
	return "[object Foo]";
}
 
var f = new Foo();
alert(f);  // popup displays [object Foo]

In this case, because of the presence of the toString() method, which overrides the default, a custom string can be displayed for the object that is more applicable to what it is. Additionally, information about the properties of the object could be included in this method as well, as in:

function Foo() 
{
	this.message = "Hello World!";
}
Foo.prototype.toString = function()
{
	return "[object Foo <" + this.message + ">]";
}
 
var f = new Foo();
alert(f);  // popup displays [object Foo <Hello World!>]

Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images