javascript 的with 語句的使用法

來源:互聯網
上載者:User

網頁特效 的with 關鍵字, with 語句的原本用意是為逐級的對象訪問提供命名空間式的速寫方式. 也就是在指定的代碼地區, 直接通過節點名稱調用對象.


with(object){
      code;
    }

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
inp1 = 1;
inp2 = 2;
inp3 = 3;
with (Math)
{
    alert("The largest number entered was " + max(inp1, inp2, inp3));
    alert("The smallest number entered was " + min(inp1, inp2, inp3));
}
//  -->
</script>
</head>
<body>

</body>
</html>

執行個體二

<html>
    <script language="JavaScript">
    <!--
    var myNum = 25;

    var myE, mySin, mySqrt;

    with (Math) {
       myE = E;
       mySqrt = sqrt(myNum)
       document.writeln(mySqrt);
       mySin = sin(PI/myNum);
       document.write(mySin);
    }
    -->
    </script>
</html>

with 語句內部通過對象父節點修改數值

var root = {
 branch: {
  node: 1
 }
};
 
with(root.branch) {
 root.branch = {
  node: 0
 };
 // 顯示 1, 錯誤!
 alert(node);
}
// 顯示 0, 正確!
alert(root.branch.node);

注意:with 語句內部的節點父節點修改後, 不會同步到節點本身. 也就是說, 不能保證內外數值的一致性. 這是可能成為項目裡面隱藏性很高的 bug.

聯繫我們

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