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

Learn JavaScript in-depth with real-world projects through our JavaScript certification course. Enroll and become a certified expert to boost your career.

输出

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

更新于: 2020 年 6 月 17 日

超过 5 千次浏览

开启你的 职业生涯

完成课程,获得认证

开始学习
广告