標籤:style blog http io ar color os sp for
javascript中的with語句是什嗎?
with 語句可以方便地用來引用某個特定對象中已有的屬性,但是不能用來給對象添加屬性。要給對象建立新的屬性,必須明確地引用該對象。
看起來不懂嗎?
<!DOCTYPE html><html><head> <title>with語句</title></head><body><div id="div0" onclick="a = 1">div</div><script> var eDiv = document.getElementById("div0"); eDiv.a = 0; //因為eDiv下沒有b這個屬性, 所以b的值變成了window下的屬性, 這個沒有問題 with(eDiv) { b = 0; }; var obj = { c : 2 }; //因為obj下有c屬性, 當我們設定值的時候, c會變成設定obj的c屬性; with(obj){ console.log(c); c = 0; }; //輸出 obj = { c : 0 } console.log(obj);</script></body></html>
好吧, 我懂了,但是這個with有毛用呢(要特別注意with語句的花括弧裡面的語句跟this不一樣的)?
<!DOCTYPE html><html><head> <title>with語句</title></head><body><script> window.l = function(){console.log( arguments[0] )}; with(location) { l(hostname); l(href) };</script></body></html>
呵呵 ,好像就是少寫幾個代碼的意思麼麼噠;
(少年, 你好像知道的太多了哦);
說這個有毛用啊, 有沒有乾貨,你這個搞毛的幹活, 浪費我的時間呢, 混蛋。
<!DOCTYPE html><html><head> <title>with語句</title></head><body><input id="ipt0" value="111" onclick="console.log(value+attributes.hehe.value)" hehe="aiyobucuoo" /><!--輸出了 ==>> 111aiyobucuoo --> 臥槽,這個是怎麼回事, 沒有用到this為什麼可以把value直接輸出出來啦;</body></html>
js內部對寫在行內的onclick處理成了
function(){
with(document){
with(this){
//代碼;
}
}
}
情不自禁的感歎, 又長見識了
然後呢?
<!DOCTYPE html><html><head> <title>with語句</title></head><body><script> document.c = "dasb";</script><form> <input value="1" type="text" name="xx" /> <input value="2" type="text" name="age"/> <!---這裡擴充了自己的範圍 form的範圍 以及documen的範圍 ----> 點擊彈出clickMe12dasb <input type="button" value="clickMe" onclick="alert(value+age.value+xx.value+c)" /></form><script> /*form擴充的範圍的方式可以看成是; with(document){ with(this.form){ with(this){ } } } */</script></body></html>
懂了沒:略懂略懂....
js中的with語句