日期:2014-05-16  浏览次数:20335 次

关于JavaScript的with语句

JavaScript 有个 with 关键字, with 语句的原本用意是为逐级的对象访问提供命名空间式的速写方式. 也就是在指定的代码区域, 直接通过节点名称调用对象.

用过 Java 和 .NET 的同学对包或命名空间的概念应该不会陌生, 正因为有这个概念, 使代码的简洁易读得到了保证. 不知 JavaScript 设计之初是如何定位 with 语句的, 个人觉得它们之间有一定的相似度. 如:

?

1
2
apple.banana.candy.dog.egg.fog.god.huh.index = 0;
doSomething(apple.banana.candy.dog.egg.fog.god.huh.index);

利用 with 语句, 可以写为以下代码.

1
2
3
4
with(apple.banana.candy.dog.egg.fog.god.huh) {
	c = 0;
	doSomething(index);
}

看起来很美妙, 却存在致命的缺陷. 下面我们来进行一些小测试吧.

1. 在 with 语句内部通过内部变量修改数值

1
2
3
4
5
6
7
8
9
10
11
12
13
var root = {
	branch: {
		node: 1
	}
};
?
with(root.branch) {
	node = 0;
	// 显示 0, 正确!
	alert(node);
}
// 显示 0, 正确!
alert(root.branch.node);

2. 在 with 语句内部通过对象节点修改数值