JavaScript with 关键字


JavaScript with 关键字

<html>
   <head>
   <title>User-defined objects</title>

      <script type = "text/javascript">
         // 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("Perl", "Mohtashim");
         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>