1 JavaScript中的with語句的做用是爲逐級的對象訪問提供命名空間式的速寫方式, 也就是在指定的代碼區域, 直接經過節點名稱調用對象css
初次接觸到with用法,是這樣一段代碼:html
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的用法總結以下:web
with對象可以使咱們很方便的使用某個對象的一些屬性,而不用每次都去寫對象名.屬性 的形式,直接使用對象名。就像上面的代碼,field是對象,而value是對象的值。若不是有with,咱們應該是field.value的形式來使用屬性。使用with去除了屢次寫with對象只能使用屬性,而不能改變屬性。優化
這裏有個很簡單的例子:this
傳統的寫法spa
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寫法ssr
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);
}
|
這樣使用,會獲得結果:code
姓名: kobe bryantorm
年齡:28htm
性別: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';
}
|