with关键字用作引用对象的属性或方法的一种简写形式。
指定为with的参数的对象在随后的块持续时间内成为默认对象。可以使用该对象的属性和方法而无需命名该对象。
with对象的语法如下-
with (object){ properties used without the object name and dot }
您可以尝试学习以下代码,以了解如何使用关键字实现-
<html> <head> <title>User-defined objects</title> <script> //定义一个将用作方法的函数 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", "Nhooo"); 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 : Nhooo Book price is : 100