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


with 關鍵字用作引用物件的屬性或方法的一種速記。

指定為 with 引數的物件將成為後續程式碼塊期間的預設物件。可以使用該物件的屬性和方法,而無需指定物件名稱。

語法

for 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

更新於: 2020 年 6 月 17 日

超過 5 千次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.