位置:首頁 > Web開發 > Javascript教學 > Javascript Object.prototype

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