Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to rely on Function.prototype.toString?

Is it safe to rely on Function.prototype.toString to return a string that will parse as a valid javascript function (for user-defined functions)?

Are there any commonly-used javascript engines that deviate from the norm as far as how they represent function objects in string form?

I have seen this question, but I'm not sure if it's asking the same thing. I don't care if the formatting is exactly the same in all implementations or whatever, I'm more worried about some minified js engine just stripping out the whole function body...

Another related question, but not closely related enough to have a satisfying answer for this question.

like image 240
Dagg Nabbit Avatar asked Dec 10 '11 04:12

Dagg Nabbit


Video Answer


2 Answers

I think it's safe since it's a standard. Every serious engine would do. That's also what my project Jscex is based on. It works for all the browsers (even the legacy IE6) and Node.js. I do this kind of things for year. :)

like image 176
Jeffrey Zhao Avatar answered Sep 24 '22 05:09

Jeffrey Zhao


It should be noted that eval'd code will take on the current scope and the Function constructor will only take on the global scope.

function createClosure() {
    var x = 20,
        y = 10;

    // Doesn't know what x & y are
    var fn = new Function("return x + y");

    // Evaluates normally
    var result = eval("x + y");
}
like image 29
Winston Tamblyn Avatar answered Sep 20 '22 05:09

Winston Tamblyn