1 JavaScript中的with语句的作用是为逐级的对象访问提供命名空间式的速写方式, 也就是在指定的代码区域, 直接通过节点名称调用对象
初次接触到with用法,是这样一段代码:
1
2
3
4
5
6
7
8
9
10
11
12
|
function validate_email(field,alerttxt){
with (field){
apos=value.indexOf(@)
dotpos=value.lastIndexOf(.)
if (apos<1||dotpos-apos<2){
alert(alerttxt);
return false;
}else {
return true;
}
}
}
|
with的用法总结如下:
with对象能够使我们很方便的使用某个对象的一些属性,而不用每次都去写对象名.属性 的形式,直接使用对象名。就像上面的代码,field是对象,而value是对象的值。若不是有with,我们应该是field.value的形式来使用属性。使用with去除了多次写with对象只能使用属性,而不能改变属性。
这里有个很简单的例子:
传统的写法
1
2
3
4
5
6
7
8
9
10
11
|
function Lakers(){
this.name = "kobe bryant";
this.age = 28;
this.gender = "boy";
}
//传统写法
var people=new Lakers();
var str = "姓名:" + people.name + "<br />";
str += "年龄:" + people.age + "<br />";
str += "性别:" + people.gender;
document.write(str);
|
with写法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
function Lakers(){
this.name = "kobe bryant";
this.age = 28;
this.gender = "boy";
}
//with写法
var people=new Lakers();
with(people){
var str = "姓名:" + name + "<br />";
str += "年龄:" + age + "<br />";
str += "性别:" + gender;
document.write(str);
}
|
这样使用,会得到结果:
姓名: kobe bryant
年龄:28
性别:boy
从下例可以看出with语句的简洁明了,不过在代码的世界里是很难找到真正的完美。
1
2
3
4
5
|
with(document.forms[0]){
name.value = "lee king";
address.value = "Peking";
zipcode.value = "10000";
}
|
对应的传统写法:
1
2
3
|
document.forms[0].name.value = "lee king";
document.forms[0].address.value = "Peking";
document.forms[0].zipcode.value = "10000";
|
但是,js的解释器需要检查with块中的变量是否属于with包含的对象,这将使with语句执行速度大大下降,并且导致js语句很难被优化。为了兼顾速度与代码量可以找到一个比较折衷的方案:
1
2
3
4
|
var form = document.forms[0];
form.name.value = "lee king";
form.address.value = "Peking";
form.zipcode.value = "10000";
|
所以在以后的高效代码开发中我们应该尽可能的避免使用with语句。
2 with方式也可以用来进行样式的赋值。
js进行样式的赋值方法大家可以参考JavaScript中用cssText设置css样式
其中一种方法是:cssText方法:
1
2
3
|
var t=document.getElementById(dd);
t.style.cssText=width:200px;height:300px;
|
还可以
1
2
3
4
|
with(t.style){
width='300px';
height='300px';
}
|