Maison  >  Article  >  interface Web  >  Comment ajouter des propriétés et des méthodes aux objets en JavaScript ?

Comment ajouter des propriétés et des méthodes aux objets en JavaScript ?

WBOY
WBOYavant
2023-08-27 21:29:10640parcourir

Comment ajouter des propriétés et des méthodes aux objets en JavaScript ?

Pour ajouter des propriétés et des méthodes aux objets en JavaScript, utilisez l'attribut prototype.

Exemple

Vous pouvez essayer d'exécuter le code suivant pour voir comment utiliser le 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>

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer