js中的with語句

來源:互聯網
上載者:User

標籤: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語句

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.