如何在 JavaScript 中向物件新增屬性和方法?


若要向 JavaScript 中的物件新增屬性和方法,請使用 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>

更新於:2020-06-23

210 人瀏覽

開啟你的 職業

透過完成課程獲得證書

開始
廣告
© . All rights reserved.