js中的with语句

1. with语句的语法

with (expression) {
    statement;
}

  

  

2. with语句的作用:是将 statement 中的变量作用域添加到 expression 中.

  with语句中查询变量顺序:

  (1) 是否是 with语句中的局部变量,如果不是则进行(2)

  (2) 是否是 expression中的变量,如果不是则进行(3)

  (3) 查找更高作用域范围.

3. 示例

	var foo = 1;
	var bar = {
		foo : 2
	}
	with (bar) {
		alert(foo);
		foo = 3;
		alert(foo);
		var foo = 4;
		alert(foo)
	}
	alert(bar.foo);
	alert(foo);
	if(true){
		foo = 5;
	}
	alert(foo);

  

  这几个alert分别打印的是: 2, 3,4,4,1, 5.

原文地址:https://www.cnblogs.com/wangdapeng/p/5595817.html