toString() and toSource() in JavaScript
March 30, 2007Did you know that you could call toSource() on a JavaScript method object to see the source code? An example using a random method on my Google personalized homepage:
1 2 |
>>> _xsetp.toSource(); "function _xsetp(a) {ig_s.push(a);if (!ig_t) {ig_K();}}" |
toString() is even better. It formats the code for human consumption:
1 2 3 4 5 6 7 |
>>> _xsetp.toString(); "function _xsetp(a) { ig_s.push(a); if (!ig_t) { ig_K(); } }" |
This is especially useful when using FireBug to inspect a website to see how it works. Use the “Inspect” feature to look at the onClick handler, then call toString() on the method in the FireBug console to see the source.
JavaScript (as defined by ECMAScript) is really a great dynamic language. It’s too bad so many developers can’t shake the bad taste in their mouths left from poor and inconsistent browser support.