Section 24.147. Object.valueOf( ): the primitive value of the specified object


24.147. Object.valueOf( ): the primitive value of the specified object

ECMAScript v1

24.147.1. Synopsis

object.valueOf( )

24.147.1.1. Returns

The primitive value associated with the object, if any. If there is no value associated with object, returns the object itself.

24.147.2. Description

The valueOf( ) method of an object returns the primitive value associated with that object, if there is one. For objects of type Object, there is no primitive value, and this method simply returns the object itself.

For objects of type Number, however, valueOf( ) returns the primitive numeric value represented by the object. Similarly, it returns the primitive boolean value associated with a Boolean object and the string associated with a String object.

It is rarely necessary to invoke the valueOf( ) method yourself. JavaScript does this automatically whenever an object is used where a primitive value is expected. In fact, because of this automatic invocation of the valueOf( ) method, it is difficult to even distinguish between primitive values and their corresponding objects. The typeof operator shows you the difference between strings and String objects for example, but in practical terms, you can use them equivalently in your JavaScript code.

The valueOf( ) methods of the Number, Boolean, and String objects convert these wrapper objects to the primitive values they represent. The Object( ) constructor performs the opposite operation when invoked with a number, boolean, or string argument: it wraps the primitive value in an appropriate object wrapper. JavaScript performs this primitive-to-object conversion for you in almost all circumstances, so it is rarely necessary to invoke the Object( ) constructor in this way.

In some circumstances, you may want to define a custom valueOf( ) method for your own objects. For example, you might define a JavaScript object type to represent complex numbers (a real number plus an imaginary number). As part of this object type, you would probably define methods for performing complex addition, multiplication, and so on (see Example 9-2). But you might also want to treat your complex numbers like ordinary real numbers by discarding the imaginary part. To achieve this, you might do something like the following:

 Complex.prototype.valueOf = new Function("return this.real"); 

With this valueOf( ) method defined for your Complex object type, you can, for example, pass one of your complex number objects to Math.sqrt( ), which computes the square root of the real portion of the complex number.

24.147.3. See Also

 Object.toString( ) 




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net