JSLint “eval is evil.” alternatives

后端 未结 7 1486
别那么骄傲
别那么骄傲 2021-02-13 22:49

I am have some JavaScript functions that run on both the client (browser) and the server (within a Java Rhino context). These are small functions - basically little validators

7条回答
  •  耶瑟儿~
    2021-02-13 23:21

    I wouldn't worry about it since you are only passing these function strings from the server to the client, and are thus in control of what will be evaluated.

    On the other hand, if you were going the other direction and doing the evals of client-passed code on the server, that would be an entirely different story...

    Update:

    As disabling the validation option in your comment may cause you to miss future errors, I would instead suggest passing the function name rather than the entire function and have the function library mirrored on the server and client. Thus, to call the function, you'd use the following code:

    var policyFunction = YourLibraryName[this.policies[j].policyFunctionName];
    var policyArguments = this.policies[j].policyArguments;
    
    policyFunction.apply(this, policyArguments); 
    

    Update 2:

    I was able to validate the following code with JSLint successfully, which essentially allows you to "turn off" validation for the vast minority of cases where eval is appropriate. At the same time, JSLint still validates normal eval calls, and all uses of this method should throw up flags for future developers to avoid using it/refactor it out where possible/as time allows.

    var EVAL_IS_BAD__AVOID_THIS = eval;
    EVAL_IS_BAD__AVOID_THIS();
    

提交回复
热议问题