JSDrip #14 - toString

55 views
Skip to first unread message

Benjamin Miller

unread,
Apr 16, 2013, 11:03:20 AM4/16/13
to js-drip-d...@googlegroups.com
toString can be a fun/useful way to manipulate predefined functions or values that are not available to the global scope.

function foo(){
 
var fooVar = "Foo Var Value"; //define variable not available to public scope
  console
.log(fooVar);
}

foo
() //will log "Foo Var Value"

//manipulate fooVar from outside where it is accessible.
eval(foo.toString().replace("Foo", "New Foo"));

foo
() //will log "New Foo Var Value"

This is very extremely hacky and I don't recommend this using this in every day code.
But it's good to know what is possible. It also serves as a good reminder; Nothing is private in JavaScript.




Joshua Clanton

unread,
Apr 17, 2013, 10:00:51 AM4/17/13
to js-drip-d...@googlegroups.com
Whoa! That's super hacky, but totally awesome.

I knew that Angular does some funky stuff with reading a function's toString value, to do dependency injection, but I had no idea that you could manipulate the function's string representation directly like that.

Let me walk through to make sure that I'm understanding, correctly, though.
  1. We get the function's string value (which is the same as the text that declared it).
  2. We manipulate that text, replacing "Foo" with "New Foo".
  3. We eval the resulting string, which declares a new function "foo" with a different definition than the previous function "foo".
Doesn't that mean that in fact, the variables in the original "foo" were private? And we've just got an entirely new "foo" with a different set a variables?

Regardless of the details, that's crazy and cool. :-)

Joshua Clanton

Benjamin Miller

unread,
Apr 17, 2013, 12:19:11 PM4/17/13
to js-drip-d...@googlegroups.com
You've got it.

Yes, you are correct. We are not technically overwriting var fooVar but the function foo().
So var fooVar would remain private to it's scope.  
Closing variables and methods in a lexical scope is a good way to mimic the privacy one would find in other languages.





Miguel Angel Frias Bonfil

unread,
Jun 18, 2013, 9:42:36 AM6/18/13
to js-drip-d...@googlegroups.com
Awesome, hacky, but awesome.

The background over here, is that functions, are also objects, they inherit some methods, like .toString.
Reply all
Reply to author
Forward
0 new messages