简体   繁体   English

评估和功能范围

[英]Eval and function scope

Something seems wrong with the following code. 以下代码似乎有问题。 It declares a function with eval , calls it — until then, everything is fine — and, calls it again but, though a function and thus gets an error. 它使用eval声明一个函数,然后调用它-直到那时,一切都很好-并且再次调用它,但是,尽管该函数会出现错误。

var fn = function() {
    return isTwo(2);
};
var check = function() {
    eval("var isTwo = function(value) { return value == 2 }")
    console.log(isTwo(2)); // returns true
    console.log(fn()); // returns isTwo is not defined
}
check();

Unwrapping the check function made things works, but seems wrong. 解开check功能可以使事情正常,但似乎是错误的。 Why using eval inside of a function should change its behavior? 为什么在eval内部使用eval应该更改其行为?

var fn = function() {
    return isTwo(2);
};

eval("var isTwo = function(value) { return value == 2 }")
console.log(isTwo(2)); // returns true
console.log(fn()); // returns true

Because eval acts as if you had replaced the line with the code to be evaluated. 因为eval就像您用要评估的代码替换了该行一样。 Therefore, var isTwo = function(value) { return value == 2 } defines a local variable, and it can't be accessed by your other function. 因此, var isTwo = function(value) { return value == 2 }定义了一个局部变量,其他函数无法访问它。 The reason it works in the outer block is because it is then a global variable, and can be accessed by your other function. 它在外部块中起作用的原因是因为它是一个全局变量,并且可以由其他函数访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM