Returns the primitive value of the specified object.
Method of Object
Syntax
valueOf()
Parameters
None
Description
MetaScript calls the valueOf method to convert an object to a primitive value. You rarely need to invoke the valueOf method yourself; MetaScript automatically invokes it when encountering an object where a primitive value is expected.
By default, the valueOf method is inherited by every object descended from Object. Every built-in core object overrides this method to return an appropriate value. If an object has no primitive value, valueOf returns the object itself, which is displayed as:
[object Object]
You can use valueOf within your own code to convert a built-in object into a primitive value. When you create a custom object, you can override Object.valueOf to call a custom method instead of the default Object method.
Overriding valueOf for custom objects
You can create a function to be called in place of the default valueOf method. Your function must take no arguments.
Suppose you have an object type myNumberType and you want to create a valueOf method for it. The following code assigns a user-defined function to the object's valueOf method:
With the preceding code in place, any time an object of type myNumberType is used in a context where it is to be represented as a primitive value, MetaScript automatically calls the function defined in the preceding code.
An object's valueOf method is usually invoked by MetaScript, but you can invoke it yourself as follows:
Note:
Objects in string contexts convert via the Object.toString method, which is different from String objects converting to string primitives using valueOf. All string objects have a string conversion, if only "[object type]". But many objects do not convert to number, boolean, or function.