Вы находитесь на странице: 1из 5

1/21/2014

Conversion, toString and valueOf | JavaScript Tutorial


Log in

JavaScript Tutorial
Home Tutorial JavaScript: from the Ground to Closures Mastering data types
Array Four scents of "this" Tutorial

JavaScript: from the Ground to Closures


JavaScript: from the Ground to Closures Javascript and related technologies First Steps Functions: declarations and expressions Mastering data types
Mastering data types String Number, Math Objects Array Conversion, toString and valueOf

Conversion, toString and valueOf


Ilya Kantor

1. String conversion 1. The algorithm of Object to String conversion 2. Custom t o S t r i n g 2. Numeric conversion 1. Custom v a l u e O fexample 3. Conversion in equality/comparison tests 4. Boolean context 5. Summary Objects in JavaScript can be converted to primitives in three contexts: 1. Numeric 2. String 3. Boolean

Like

Four scents of "this" Type detection Function arguments Static variables and methods Scopes and Closures Decorators

Understanding the way conversion works helps to evade possible pitfalls and write cleaner code.

String conversion
String conversion happens when a string representation of an object is required. For example, in a l e r t ( o b j )does it to output o b j :
Run!

Document and Events Object Oriented Programming Timing Frames and windows Regular expressions in JavaScript Advanced and Extra stuff

1 v a ro b j={n a m e :' J o h n '} 2 3 a l e r t ( o b j )/ /[ o b j e c tO b j e c t ] The explicit conversion is also possible: S t r i n g ( o b j ) .

The algorithm of Object to String conversion


1. If t o S t r i n gmethod exists and returns a primitive, then return it. Execution normally stops here, because t o S t r i n gexists on all objects by default. 2. If v a l u e O fmethod exists and returns a primitive, then return it. 3. Otherwise, throw an exception. Again, normally all objects have t o S t r i n g . Built-in objects have their own t o S t r i n gimplementations:
Run!

Donate Donate to this project

1 a l e r t ({ k e y :' v a l u e ' })/ /t o S t r i n gf o rO b j e c t so u t p u t s :[ o b j e c tO b j e c t ] 2 a l e r t ([ 1 , 2 ]) / /t o S t r i n gf o rA r r a y sl i s t se l e m e n t s" 1 , 2 " 3 a l e r t (n e wD a t e) / /t o S t r i n gf o rD a t e so u t p u t st h ed a t ea sas t r i n g

Custom t o S t r i n g
For our objects, we can implement a custom t o S t r i n g :
Run!

0 1 v a ru s e r={ 0 2 0 3 f i r s t N a m e :' J o h n ' , 0 4 0 5 t o S t r i n g :f u n c t i o n ( ){ 0 6 r e t u r n' U s e r'+t h i s . f i r s t N a m e 0 7 } 0 8 } 0 9 1 0 a l e r t (u s e r) / /U s e rJ o h n

Numeric conversion
There is another conversion in JavaScript, not as wide known as t o S t r i n g , but internally it is called much more often.

http://javascript.info/tutorial/object-conversion

1/5

1/21/2014
Numeric conversion is performed in two main cases:

Conversion, toString and valueOf | JavaScript Tutorial

In functions which needs a number: for example M a t h . s i n ( o b j ) ,i s N a N ( o b j ) , including arithmetic operators: + o b j . In comparisons, like o b j= =' J o h n ' . The exceptions are the string equality = = = , because it doesnt do any type conversion, and also nonstrict equality when both arguments are objects, not primitives: o b j 1= =o b j 2 . It is true only if both arguments reference the same object. The explicit conversion can also be done with N u m b e r ( o b j ) . The algorithm of numeric conversion: 1. If v a l u e O fmethod exists and returns a primitive, then return it. 2. Otherwise, if t o S t r i n gmethod exists and returns a primitive, then return it. 3. Otherwise, throw an exception. Among built-in objects, D a t esupports both numeric and string conversion:
Run!

1 a l e r t (n e wD a t e ( ))/ /T h ed a t ei nh u m a n r e a d a b l ef o r m 2 a l e r t (+ n e wD a t e ( ))/ /M i c r o s e c o n d st i l l1J a n1 9 7 0 But most objects do not have v a l u e O f . It means that numeric conversion is handled by t o S t r i n g .

Custom v a l u e O fexample
The magic method v a l u e O fcan be customized, just like t o S t r i n g :
Run!

0 1 v a rr o o m={ 0 2 0 3 n u m :7 7 7 , 0 4 0 5 v a l u e O f :f u n c t i o n ( ){ 0 6 r e t u r nt h i s . n u m 0 7 } 0 8 } 0 9 1 0 a l e r t (+ r o o m) / /7 7 7 If there is a custom t o S t r i n g , but no v a l u e O f , the interpreter will use it for numeric conversion:
Run!

0 1 v a rr o o m={ 0 2 0 3 n u m :7 7 7 , 0 4 0 5 t o S t r i n g :f u n c t i o n ( ){ 0 6 r e t u r nt h i s . n u m 0 7 } 0 8 } 0 9 1 0 a l e r t (r o o m/3) / /2 5 9

Numeric conversion and being a number


Numeric conversion does not mean, that a number is returned. It must return a primitive, but there is no limitation on its concrete type. Because of that, a good way to convert an object to a string is the binary addition:
Run!

1 2 3 4 5

v a ra r r=[ 1 , 2 , 3 ] a l e r t (a r r+' ') / /f i r s tt r i e sa r r . v a l u e O f ( ) ,b u ta r r a y sh a v en ov a l u e O f / /s oa r r . t o S t r i n g ( )i sc a l l e da n dr e t u r n sal i s to fe l e m e n t s : ' 1 , 2 , 3 '

For historical reasons, n e wD a t e+' 'also returns a string representation of D a t eeven though n e wD a t ehas v a l u e O f . Thats an exception.

Other mathematical functions not only perform the numeric conversion, but enforce a number. For example, the unary addition + a r rwould give N a N :
Run!

1 a l e r t (+ [ 1 , 2 , 3 ])/ /[ 1 , 2 , 3 ]>' 1 , 2 , 3 '>n o tan u m b e r

Conversion in equality/comparison tests


http://javascript.info/tutorial/object-conversion 2/5

1/21/2014

Conversion, toString and valueOf | JavaScript Tutorial

Non-strict equality and comparisons use numeric context. The equality converts an object only if it is compared against a primitive: i f( o b j= =t r u e ){. . .} There will no be conversion in equity check for two objects: o b j 1= =o b j 2is true only if they refer to the same object. The comparison always converts to primitive:
Run!

1 2 3 4 5 6 7 8

v a ra={ v a l u e O f :f u n c t i o n ( ){r e t u r n 1} } v a rb ={ v a l u e O f :f u n c t i o n ( ){r e t u r n 0} } a l e r t (a>b) / /1>0 ,t r u e

Why the following is true?


Run!

1 a l e r t ([ ' x ' ]= =' x ')

Open solution

Boolean context
There is one more standard conversion in JavaScript, called [ [ t o B o o l e a n ] ]in the specification. If happens in boolean context, like i f ( o b j ) ,w h i l e ( o b j )etc. Object may not implement such conversion on their own, there is no magic method. Instead, there is a hardcoded table of conversions: Value t r u e / f a l s e u n d e f i n e d ,n u l l N u m b e r S t r i n g O b j e c t Converted to no conversion f a l s e 0 ,N a Nbecome f a l s e , others - t r u e . " "becomes f a l s e , any other - t r u e t r u e

'
Unlike many programming languages (for example PHP), " 0 "is t r u ein JavaScript.

In the example below, we have numeric conversion (equality does it):


Run!

1 a l e r t ([ 0 ]= =0) / /t r u e 2 a l e r t (" \ n 0 \ n "= =0)/ /t r u e 3 a l e r t (" \ n 0 \ n "= =f a l s e)/ /t r u e So one may guess that [ 0 ]and " \ n 0 \ n "are falsy, because they equal 0 . But now lets see how the left part behaves in boolean context:
Run!

1 i f( [ 0 ] )a l e r t ( 1 ) / /1 ,i ft r e a t s[ 0 ]a st r u e 2 i f( " \ n 0 \ n " )a l e r t ( 2 )/ /2 ,i ft r e a t s" \ n 0 \ n "a st r u e It is possible that a = =b , but in boolean context ais t r u eand bis f a l s e .

A way to frighten Java programmers. To convert a value to boolean, you may use double-negation: ! ! v a lor direct call B o o l e a n ( v a l ) . Of course, we never use n e wB o o l e a nfor any purpose. Funny things happen if we do. For example, lets try to get a boolean out of zero:
Run!

http://javascript.info/tutorial/object-conversion

3/5

1/21/2014

Conversion, toString and valueOf | JavaScript Tutorial


1 a l e r t (n e wB o o l e a n ( f a l s e ))/ /f a l s e But
Run!

1 i f(n e wB o o l e a n ( f a l s e )){ 2 a l e r t ( t r u e )/ /t r u e 3 } Thats because n e wB o o l e a nis an object. The a l e r tconverts it to String, and it becomes " f a l s e " Right. But i fconverts it to boolean primitive, and here any object is true Wops! Java programmers eyes usually pop out when they see that.

Why they are equal?


Run!

1 a l e r t ([ ]= =! [ ])/ /t r u e

Open solution

Figure out the result of expressions. When you are done, check against the solution. 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 0 1 1 1 2 1 3 6/" 3 " " 2 "*" 3 " 4+5+" p x " " $ "+4+5 " 4 "-2 " 4 p x "-2 7/0 { } [ 0 ] p a r s e I n t ( " 0 9 " ) 5& &2 2& &5 5| |0 0| |5

Open solution

Summary
There are three conversions in JavaScript, which depend on the context: 1. String: output, uses t o S t r i n g . 2. Numeric: maths, operators, uses v a l u e O f-> t o S t r i n g . 3. Boolean: converts according to the table. Thats different from most other programmer languages, But simple when you get it. P.S. Actually, the conversion is a bit more sophisticated than described here. Ive left out a good bit of complexity to concentrate on how it really works. For a maximally precise conversion algorithms, refer to the specification: ECMA-262 5th ed., especially 11.8.5 (relational comparison), and 11.9.3 (equality comparison) and 9.1 (toPrimitive) and 9.3 (toNumber). Array Four scents of "this"

The content of this site is available under the terms of CC BY-NC-SA. Ilya Kantor, 2011.

"JavaScript is a registered trademark of Oracle corp. This site is not affiliated with Oracle corp.

http://javascript.info/tutorial/object-conversion

4/5

1/21/2014

Conversion, toString and valueOf | JavaScript Tutorial

http://javascript.info/tutorial/object-conversion

5/5

Вам также может понравиться