Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating stringification of booleans

Tags:

javascript

Is it possible to manipulate the way booleans are stringified?

Changing Boolean.prototype.toString doesn't seem to help.

Here my tests within mozrepl and FF3.

repl> Boolean.prototype.toString=function (){return this==true ? "1" : ""}
function() {…}
repl> a.toString()
""
repl> a=true
true
repl> a.toString()
"1"
repl> a+""
"true"
repl> a=false
false
repl> a+""
"false"

My understanding of the ECMA specification is that + should call toString().


UPDATE:

OK I found the answer!

When ECMA speaks about ToString() it doesn't mean the JS method toString().

These operators are not a part of the language; they are defined here to aid the specification of the semantics of the language.

see http://bclary.com/2004/11/07/#a-9

Thanks for the help so far.

Doesn't seem to be possible... :(

like image 731
LanX Avatar asked Oct 08 '11 22:10

LanX


2 Answers

I suppose .toString() is called on the Boolean version of the native boolean type (Boolean is an Object but the native type isn't, same with Numbers) and + is overloaded by the browser to convert a boolean to a string natively.

This question has been asked before (and I'm fairly sure what I said was the answer) but I can't seem to find it.

like image 147
Ry- Avatar answered Oct 24 '22 04:10

Ry-


Looks like you found the answer, but for reference:

Section 11.6.1 explains what happens when + is invoked on a string and another value.

If Type(lprim) is String or Type(rprim) is String, then Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)

and as you noted, ToString is not just a call to toString.

Section 9.8 explains what ToString does.

The abstract operation ToString converts its argument to a value of type String according to Table 13:

Boolean If the argument is true, then the result is "true". If the argument is false, then the result is "false".

Note that for objects, valueOf is invoked, not toString because ToString delegates to ToPrimitive which for native objects ends up in DefaultValue with type hint undefined

Let valueOf be the result of calling the [[Get]] internal method of object O with argument "valueOf".

If IsCallable(valueOf) is true then,

Let val be the result of calling the [[Call]] internal method of valueOf, with O as the this value and an empty argument list.

If val is a primitive value, return val.

If you want "" + new Boolean(a) to delegate to Boolean.prototype.toString you would first have to override Boolean.prototype.valueOf to return a non-primitive value which is bad manners.

like image 39
Mike Samuel Avatar answered Oct 24 '22 04:10

Mike Samuel