如何在 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.