文章出處
文章列表
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>
懂了沒:略懂略懂....
文章列表
全站熱搜