I am creating a DSL that will benefit from being able to crack some of the internal elements of JS. I understand that this is a very bad idea in general use of JS, but for my purposes it is good. The following code works fine:
var str = new String("blah"); str.valueOf = function() { return 10 } console.log(str * 10);
But this is not so:
var str = "blah"; str.valueOf = function() { return 10 } console.log(str * 10);
Can someone who understands the insides explain a little what is happening here? What is the difference between these two examples?
And now, if I want to change the String prototype itself, so I can set the valueOf method of all strings, regardless of when / where / how they are created? Is it possible? Unfortunately this does not work:
String.prototype.valueOf = function() { return 10 } console.log("blah" * 10);
Although it does:
String.prototype.valueOf = function() { return 10 } console.log("blah".valueOf() * 10);
So:
String.prototype.valueOf = function() { return 10 } console.log(new String("blah") * 10);
Why does the JS engine handle "blah" and new String("blah") differently? Thanks!
By the way, here is a good article that led me to study this material.
source share