【问题标题】:How to pass multiple variables into an "eval" expression using "with"?如何使用“with”将多个变量传递给“eval”表达式?
【发布时间】:2014-10-25 09:35:49
【问题描述】:

我正在尝试完成类似的事情:eval() with variables from an object in the scope

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

【问题讨论】:

    标签: javascript eval


    【解决方案1】:

    我不建议使用 witheval 除非作为一种学习练习,因为其中任何一个都会减慢代码速度,并且同时使用它们尤其糟糕且不受欢迎由更大的 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"
    

    编辑为使用任意数量的范围源,注意属性名称冲突。 再说一次,我通常不使用 with,但这很有趣...

    【讨论】:

    • “慢”是什么意思。使用“with”或将“with”与“eval”一起使用?此外,您的示例仅传递一个变量。你如何传递多个?
    • @John:我所说的慢是指您以这种方式作为字符串传入的登录名比您使用类似 o1.a+o2.b 的登录名执行得慢得多。 with 降低代码速度的原因是查找成本更高,而 eval 会阻止很多编译器优化。
    • 但是,如果您在运行时才知道变量的数量,那将不起作用。您实际上必须从一个字符串动态创建函数,然后执行多个 eval!
    • 正如@dandavis 所说,不推荐使用with。这就是为什么 - yuiblog.com/blog/2006/04/11/with-statement-considered-harmful
    • @John:已编辑以允许任意数量的对象作为词法名称来源。
    猜你喜欢
    • 2020-01-14
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多