新聞中心
JavaScript有個(gè) with關(guān)鍵字, with 語(yǔ)句的原本用意是為逐級(jí)的對(duì)象訪問(wèn)提供命名空間式的速寫方式. 也就是在指定的代碼區(qū)域, 直接通過(guò)節(jié)點(diǎn)名稱調(diào)用對(duì)象.

用過(guò) Java 和 .NET 的同學(xué)對(duì)包或命名空間的概念應(yīng)該不會(huì)陌生, 正因?yàn)橛羞@個(gè)概念, 使代碼的簡(jiǎn)潔易讀得到了保證. 不知 JavaScript 設(shè)計(jì)之初是如何定位 with 語(yǔ)句的, 個(gè)人覺(jué)得它們之間有一定的相似度. 如:
- apple.banana.candy.dog.egg.fog.god.huh.index = 0;
- doSomething(apple.banana.candy.dog.egg.fog.god.huh.index);
利用 with 語(yǔ)句, 可以寫為以下代碼.
- with(apple.banana.candy.dog.egg.fog.god.huh)
- {
- c = 0;
- doSomething(index);
- }
看起來(lái)很美妙, 卻存在致命的缺陷. 下面我們來(lái)進(jìn)行一些小測(cè)試吧.
1. 在 with 語(yǔ)句內(nèi)部通過(guò)內(nèi)部變量修改數(shù)值
- var root = {
- branch: {
- node: 1
- }
- };
- with(root.branch) {
- node = 0;
- // 顯示 0, 正確!
- alert(node);
- }
- // 顯示 0, 正確!
- alert(root.branch.node);
2. 在 with 語(yǔ)句內(nèi)部通過(guò)對(duì)象節(jié)點(diǎn)修改數(shù)值
- var root = {
- branch: {
- node: 1
- }
- };
- with(root.branch) {
- root.branch.node = 0;
- // 顯示 0, 正確!
- alert(node);
- }
- // 顯示 0, 正確!
- alert(root.branch.node);
經(jīng)過(guò)測(cè)試 1 和測(cè)試 2, 乍看沒(méi)什么問(wèn)題, 但是... 請(qǐng)看測(cè)試 3.
3. 在 with 語(yǔ)句內(nèi)部通過(guò)對(duì)象父節(jié)點(diǎn)修改數(shù)值
- var root = {
- branch: {
- node: 1
- }
- };
- with(root.branch) {
- root.branch = {
- node: 0
- };
- // 顯示 1, 錯(cuò)誤!
- alert(node);
- }
- // 顯示 0, 正確!
- alert(root.branch.node);
由上面的測(cè)試 3 可知, with 語(yǔ)句內(nèi)部的節(jié)點(diǎn)父節(jié)點(diǎn)修改后, 不會(huì)同步到節(jié)點(diǎn)本身. 也就是說(shuō), 不能保證內(nèi)外數(shù)值的一致性. 這是可能成為項(xiàng)目里面隱藏性很高的 bug.
那我們?cè)撛趺崔k呢? 接受那很長(zhǎng)的一串逐級(jí)訪問(wèn), 還是另有他法?
方法是有的. 我們可以通過(guò)別名引用父節(jié)點(diǎn)的方式來(lái)調(diào)用節(jié)點(diǎn)對(duì)象, 如:
- var root = {
- branch: {
- node: 1
- }
- };
- var quote = root.branch;
- quote.node = 0;
- // 顯示 0, 正確!
- alert(root.branch.node);
我相信很少人會(huì)用 with 語(yǔ)句, 也不會(huì)有很多人知道這個(gè)關(guān)鍵字, 但我覺(jué)得這是個(gè)有問(wèn)題的語(yǔ)句, 壓根就不應(yīng)該使用, 所以寫個(gè)小文記錄一下.
原文地址:http://www.neoease.com/javascript-with-statement/
本文標(biāo)題:關(guān)于JavaScript的with語(yǔ)句
網(wǎng)址分享:http://m.5511xx.com/article/dppisjc.html


咨詢
建站咨詢
