【发布时间】:2014-10-25 09:35:49
【问题描述】:
我正在尝试完成类似的事情:eval() with variables from an object in the scope
正确答案建议使用“with”关键字,但我找不到任何实际使用“with”的人的例子。有人可以解释如何使用“with”将多个变量传递到上面链接中的“eval”表达式中吗?
【问题讨论】:
标签: javascript eval
我正在尝试完成类似的事情:eval() with variables from an object in the scope
正确答案建议使用“with”关键字,但我找不到任何实际使用“with”的人的例子。有人可以解释如何使用“with”将多个变量传递到上面链接中的“eval”表达式中吗?
【问题讨论】:
标签: javascript eval
我不建议使用 with 或 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"
编辑为使用任意数量的范围源,注意属性名称冲突。 再说一次,我通常不使用 with,但这很有趣...
【讨论】:
with。这就是为什么 - yuiblog.com/blog/2006/04/11/with-statement-considered-harmful