js基礎之變數

來源:互聯網
上載者:User

代碼如下:

<style type="text/css">#myDiv { background: red;}</style>    <div id="myDiv" style="width:100px;height:100px;"></div> <script type="text/javascript">var myDiv=document.getElementById('myDiv');var CurrentStyle = function(){    return myDiv.currentStyle || document.defaultView.getComputedStyle(myDiv, null);}alert(CurrentStyle.width);</script>

前者能正確執行,即瀏覽器彈出100px;後者卻彈出undefined;

原因:不論是先定義函數後或是用函數直接返回樣式組(類數組),CurrentStyle變數始終是一個函數對象,在代碼二中它就是function(){ return……}。因此CurrentStyle.width顯然是錯誤的。可以用alert(CurrentStyle)驗證一下變數是樣式組還是函數。

驗證結果為:彈出

"function(){ return myDiv.currentStyle || document.defaultView.getComputedStyle(myDiv, null); }"
變數CurrentStyle為函數.

如果想讓代碼二輸出理想結果"100px",可以將alert(CurrentStyle.width)改為alert(CurrentStyle().width)。也就是說當變數為具體函數對象執行個體時,要在變數名後加"()"來表示其代表的完整的函數執行結果。可以理解為function(){}()。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.