How to add properties and methods to an object in JavaScript?

HTMLJavascriptProgramming Scripts

To add properties and methods to an object in JavaScript, use the prototype property.

Example

You can try to run the following code to learn how to work with prototype −

<html>
   <head>
      <title>JavaScript prototype property</title>
      <script>
         function book(title, author) {
            this.title = title;
            this.author = author;
         }
      </script>
   </head>
   <body>
      <script>
         var myBook = new book("Amit", "Java");
         book.prototype.price = null;
         myBook.price = 500;

         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>
raja
Published on 26-Feb-2018 08:07:17
Advertisements