Object.toString

Returns a string representing the specified object.

Method of Object

Syntax

toString()

Description

Every object has a toString method that is automatically called when it is to be represented as a text value or when an object is referred to in a string concatenation.
By default, the toString method is inherited by every object descended from Object. You can override this method for custom objects that you create. If you do not override toString in a custom object, toString returns [object type], where type is the object type or the name of the constructor function that created the object.
For example:

Built-in toString methods

Every built-in core MetaScript object overrides the toString method of Object to return an appropriate value. MetaScript calls this method whenever it needs to convert an object to a string.

Overriding the default toString method

You can create a function to be called in place of the default toString method. The toString method takes no arguments and should return a string. The toString method you create can be any value you want, but it will be most useful if it carries information about the object.
The following code defines the Dog object type and creates theDog, an object of type Dog:

If you call the toString method on this custom object, it returns the default value inherited from Object:

The following code creates dogToString, the function that will be used to override the default toString method. This function generates a string containing each property, of the form "property = value;".

The following code assigns the user-defined function to the object's toString method:

With the preceding code in place, any time theDog is used in a string context, MetaScript automatically calls the dogToString function, which returns the following string:

Dog Gabby is [
name is Gabby;
breed is Lab;
color is chocolate;
sex is girl;
]

An object's toString method is usually invoked by MetaScript, but you can invoke it yourself as follows:

See also

Object.toSource, Object.valueOf

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.