Security considerations using “new Function(…)” (during rendertime, expression coming from my Javascript sources)

后端 未结 4 1142
小蘑菇
小蘑菇 2021-01-13 02:09

I\'d like to use new Function(...) to generate a function from very reduced code. I\'l like to do this to

  • avoid parsing the expression on my own
4条回答
  •  一个人的身影
    2021-01-13 02:13

    Security-wise both are just as bad if user input is allowed to break out in the code. However, maintenance wise you don't have to worry about hidden bugs when local eval messes with your scope and causes dynamic scoping.

    Performance-wise the function generated by new Function is exactly the same as any other function. The generation is slower but inlike eval it doesn't cause the containing scope to be unoptimizable.

    In fact, new Function can be used to improve performance in situations like:

    //Will behave like function a( obj ) { return obj.something }
    function makePropReader( propName ) {
        return new Function( "obj", "return obj." + propName );
    }
    

    The constructed function will perform better than the function returned here:

    function makePropReader( propName ) {
         return function( obj ) {
             return obj[propName];
         }
    }
    

    Due to having to dynamically read propName from closure context and do a dynamic read on the object everytime it is called.

提交回复
热议问题