JavaScript 对象 – 原型
描述
原型属性允许您向任何对象(Number、Boolean、String 和 Date 等)添加属性和方法。
注意 − 原型是一个全局属性,几乎在所有对象中都可用。
语法
它的语法如下所示 −
object.prototype.name = value
示例
尝试以下示例。
<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