Home >Web Front-end >HTML Tutorial >How to add properties and methods to objects in JavaScript?

How to add properties and methods to objects in JavaScript?

WBOY
WBOYforward
2023-08-27 21:29:10690browse

How to add properties and methods to objects in JavaScript?

To add properties and methods to objects in JavaScript, use the prototype attribute.

Example

You can try running the following code to understand how to use the 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>

The above is the detailed content of How to add properties and methods to objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete