如何将多个变量传递到“;eval”;使用“;带有“;

How to pass multiple variables into an "eval" expression using "with"?

本文关键字:eval 带有 使用 变量      更新时间:2023-09-26

我正试图用作用域中对象的变量来完成类似in:eval()的操作

正确的答案建议使用"with"关键字,但我找不到任何人真正使用"with"的例子。有人能解释一下如何使用"with"将多个变量传递到上面链接中的"eval"表达式中吗?

我不建议将eval一起使用,除非是作为一种学习练习,因为其中任何一种都会减慢代码的速度,同时使用它们尤其糟糕,更大的js社区对此表示不满。

但它确实有效:

function evalWithVariables(code) {
  var scopes=[].slice.call(arguments,1), // an array of all object passed as variables
  A=[], // and array of formal parameter names for our temp function
  block=scopes.map(function(a,i){ // loop through the passed scope objects
        var k="_"+i;  // make a formal parameter name with the current position
        A[i]=k;  // add the formal parameter to the array of formal params
        return "with("+k+"){"   // return a string that call with on the new formal parameter
  }).join(""), // turn all the with statements into one block to sit in front of _code_
  bonus=/'breturn/.test(code) ? "": "return "; // if no return, prepend one in
   // make a new function with the formal parameter list, the bonus, the orig code, and some with closers
  // then apply the dynamic function to the passed data and return the result
  return Function(A, block+bonus+code+Array(scopes.length+1).join("}")).apply(this, scopes);  
}
evalWithVariables("a+b", {a:7}, {b:5}); // 12
evalWithVariables("(a+b*c) +' :: '+ title ", {a:7}, {b:5}, {c:10}, document);
// == "57 :: javascript - How to pass multiple variables into an "eval" expression using "with"? - Stack Overflow"

编辑为使用任意数量的作用域源,请注意属性名称冲突。再说一遍,我通常不会将一起使用,但这有点有趣。。。