Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I subclass Boolean to change string representation without negative side effects outside of my function?
    primarykey
    data
    text
    <p>I need to a way to wrap a boolean value such that comparisons are not broken and the string result is different than 'false' or 'true' without altering the global boolean values</p> <pre><code>function TestIt(bool){ if(wrapper(bool) == true) return "it was: " + wrapper(bool) if(wrapper(bool) == false) return "it was: " + wrapper(bool) return "no dice" } </code></pre> <p>e.g.</p> <pre><code>var result; result = TestIt(true); // "it was: True" result = TestIt(false); // "it was: False" </code></pre> <p>The attempts I have written have not been able to achieve all of the conditions below at the same time:</p> <pre><code>var initial = true; var result1; var result2; (function(){ result1 = wrapper(true); result2 = wrapper(true); })() // result1 == result2 // result1 == true // result1.toString() != initial.toString() // initial.toString() == true.toString() // initial.toString() == (new Boolean(true)).toString() </code></pre> <p>Can anyone help me please?</p> <p>I need this (automatic) alternate string conversion so that I can duplicate a string created on a server environment using a different language and match it exactly. </p> <p>~~~~~~</p> <p>Edit</p> <p>~~~~~~</p> <p>I forgot to mention that the trouble I am running into is the Boolean "valueOf" method that is called instead of toString (apparently) for string concatenation. </p> <p>~~~~~~</p> <p>Edit #2</p> <p>~~~~~~ </p> <p>This would also need to work for false. I just left that out for brevity. However, wrapper(false) == false gave me a headache.</p> <p>~~~~~~</p> <p>Edit Final</p> <p>~~~~~~</p> <p>It turns out (in the answers below), that you can't override the default behavior like I wanted if string concatenation is used. I am going to work on using an array to solve my problem and then doing custom conversions when I join it back together. It seems like Javascript requires an oddball approach to a conceptually simple problem. </p> <p>Code Example for command line:</p> <pre><code>function boolish(a){a=new Boolean(a);a.toString=function(){return this.valueOf()?"True":"False"};return a}; boolish(false) == false boolish(true) == true boolish(false) + " or " + boolish(true) [boolish(false) , " or " , boolish(true)].join("~~~~~~~~") </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload