JavaScript & jQuery Tutorials

JS Home Right Arrow JS Reference Right Arrow Object Right Arrow toString()

toString()  Object  instance method

Description

Returns a string of the specified object.

  • Automatically invoked when an object is called and a string is expected or when viewing the object as a string.
  • The Object.toString() method is inherited by all Object descendants.
  • Unless overridden by a custom object toString() returns [object Object].

Syntax


Signature Description
anObject.toString()Returns a string of the specified object.

Parameters

None.

Examples

The code below creates an object and displays it.



// Create an object.
anObject = new Object();
alert(anObject.toString() + ' anObject is an Object instance.');

Press the button below to action the above code:


Overriding The Object.toString() Method

As you can see when pressing the above button the default for toString() on an objectType of Object returns [object Object]. If you want something meaningful returned for your object, you need to override the Object.toString() method.

The code below creates a custom object type function and overrides the Object.toString() method. We then create and display a string of the object which will use our custom toString() method.


// Define a custom object type function.
function HomeOwner(firstName,lastName) {  
  this.firstName=firstName;  
  this.lastName=lastName;  
}  
// Define a custom override function for toString().
HomeOwner.prototype.toString = function HomeOwnerToString() {  
  var owns = this.firstName + ' ' + this.lastName + ' owns a house!';  
  return owns;  
}
// Create and print a HomeOwner object.
owner = new HomeOwner('Barney','Magrew');  
alert(owner.toString());

Press the button below to action the above code:

Related Tutorials

JavaScript Basic Tutorials - Lesson 7 - Objects



  

go to home page Homepage go to top of page Top