Javascript Object.prototype


prototype屬性可以將屬性和方法新增到任何物件(Number, Boolean, String 和Date等)。

註:原型(Prototype)是一個全域性的屬性,它可以使用在幾乎所有的物件。

語法

object.prototype.name = value

範例:

這裡有一個例子展示了如何使用原型(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>

這將產生以下結果:

Book title is : Perl
Book author is : Mohtashim
Book price is : 100