如何在 JavaScript 中使用 `with` 關鍵字?


使用 `with` 關鍵字作為一種縮寫,來引用物件屬性或方法。

作為 `with` 引數指定的物件,成為後續程式碼塊的預設物件。可以不使用物件名使用物件屬性和方法。

語法

使用 `object` 的語法如下 −

with (object){
   properties used without the object name and dot
}

示例

你可以嘗試學習以下程式碼以瞭解如何實現 `with` 關鍵字 −

線上演示

<html>
   <head>
      <title>User-defined objects</title>
      <script>
         // Define a function which will work as a method
         function addPrice(amount){
            with(this){
               price = amount;
            }
         }
         function book(title, author){
            this.title = title;
            this.author = author;
            this.price = 0;
            this.addPrice = addPrice; // Assign that method as property.
         }
      </script>
   </head>
   <body>
      <script type="text/javascript">
         var myBook = new book("Python", "Tutorialspoint");
         myBook.addPrice(100);

         document.write("Book title is : " + myBook.title + "<br>");
         document.write("Book author is : " + myBook.author + "<br>");
         document.write("Book price is : " + myBook.price + "<br>");
      </script>
   </body>
</html>

輸出

Book title is : Python
Book author is : Tutorialspoint
Book price is : 100

更新於:17-6-2020

5 千次以上瀏覽

助力您的 職業

完成課程認證

開始
廣告
© . All rights reserved.