關於JavaScript中name的意義衝突

來源:互聯網
上載者:User

    在昨天的《Javascript權威指南》學習筆記之十:ECMAScript 5 增強物件模型一文中,對於一段代碼的調試出現了一個奇怪現象,現將原始碼貼在下面:

<script type="text/javascript">function Person(){}        var per = new Person;Object.defineProperties(per,{"nickName":{value:"Tom",writable:true},"age":   {   value:20,   configurable:false,   writable:false   }});var o = Object.getOwnPropertyDescriptor(per,"nickName");alert(JSON.stringify(o));</script>

Google中運行結果:


這個結果是正確的,但是,改一個地方,結果就不同了

<script type="text/javascript">function Person(){}        var per = new Person;Object.defineProperties(per,{"nickName":{value:"Tom",writable:true},"age":   {   value:20,   configurable:false,   writable:false   }});var name = Object.getOwnPropertyDescriptor(per,"nickName");alert(JSON.stringify(name));</script>

運行結果:


這是為什麼呢?就只是改了一個簡單的變數名啊

問題出在了name身上,但是本人出入JS,不懂,在網上找了資料也沒有結果,後面就去請教了一個師兄,也把問題放在了論壇上:http://bbs.csdn.net/topics/390799744?page=1#post-397474060,


name是window屬性,作用是設定或返回視窗的名字,資料類型是字串。因為第一句是function Person(){},已經結束了,所以下面的代碼可能在全域context中,也就是說你以為alert(JSON.stringify(name));是輸出的上面的var name,但實際上可能輸出的是window.name。至於輸出[Object object],這個類型是name的值的類型。


聯繫我們

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