How to use the 'with' keyword in JavaScript?


The with keyword is used as a kind of shorthand for referencing an object's properties or methods.

The object specified as an argument to with becomes the default object for the duration of the block that follows. The properties and methods for the object can be used without naming the object.

Syntax

The syntax for with object is as follows −

with (object){
   properties used without the object name and dot
}

Example

You can try to learn the following code to learn how to implement with keyword −

Live Demo

<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>

Output

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

Updated on: 17-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements