eval
在非严格模式的情况下eval可以接受一个字符串来动态的改变作用域,
eval("var a=12")
function foo(str,a) {
eval(str);
console.log(a,b); //2,3
}
var b=4;
foo("var b=3",2);
console.log(window.a) //12
动态的给eval传递字符串改变了function foo的作用域。而且第一句的 eval(“var a=12”)相当于声明了一个全局变量。‘
但是在严格模式(use strict)下eval()不能使用
"use strict";
eval("var a=12")
function foo(str,a) {
eval(str);
console.log(a,b); //2,4
}
var b=4;
foo("var b=3",2);
console.log(window.a) //undefined
在输出2,4的时候这个b是由全局变量那来的。eval()不能再使用了。
所以eval()的使用不被提倡。
with关键字也会改变作用域
js中普通的with的用法
function Lakers() {
this.name = "kobe bryant";
this.age = "28";
this.gender = "boy";
}
var people=new Lakers();
with(people)
{
var str = "姓名: " + name + "<br>";
str += "年龄:" + age + "<br>";
str += "性别:" + gender;
document.write(str);
}
会在屏幕上写出
姓名: kobe bryant
年龄:28
性别:boy
with语句把a改变成了全局变量
function foo(obj) {
with(obj){
a=2;
}
}
var ob1={a:3};
foo(ob1);
console.log(ob1.a); //2
var ob2={b:2};
foo(ob2);
console.log(ob2.a); //undefined
console.log(a); //with语句会把a给改变成了全局变量
注意:严格模式下,js没有with语句
"use strict";
function foo(obj) {
with(obj){
a=2;
}
}
var ob1={a:3};
foo(ob1);
console.log(ob1.a); //2
var ob2={b:2};
foo(ob2);
console.log(ob2.a); //undefined
console.log(a); //with语句会把a给改变成了全局变量
程序就会报这样的错误:
Uncaught SyntaxError: Strict mode code may not include a with statement
运行效率会变慢
如果以上这两句话如果在程序中出现次数太多的话,就会导致运行效率变慢。
因为如果引擎在代码中发现了eval with 只能简单的假设关于标识符的位置的判断都是无效的,因为无法在此法分析阶段明确的知道eval()会接收到什么样的代码。所以写代码的时候,一般都不会使用它,但是我们需要noon搞清楚这个原理。