prototype

优质
小牛编辑
139浏览
2023-12-01

描述 (Description)

prototype属性允许您向任何对象添加属性和方法(Number,Boolean,String和Date等)。

Note - Prototype是一个全局属性,几乎可用于所有对象。

语法 (Syntax)

使用以下语法来使用Prototype。

object.prototype.name = value

例子 (Example)

请尝试以下示例以使用prototype属性向对象添加属性。

<html>
   <head>
      <title>User-defined objects</title>
      <script type="text/javascript">
         function book(title, author){
            this.title = title; 
            this.author  = author;
         }
      </script>
   </head>
   <body>
      <script type="text/javascript">
         var myBook = new book("Perl", "Mohtashim");
         book.prototype.price = null;
         myBook.price = 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 : Perl
Book author is : Mohtashim
Book price is : 100