要向 JavaScript 中的对象添加属性和方法,请使用 prototype 属性。
示例
您可以尝试运行以下代码来了解如何使用原型 -
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <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>
|
登录后复制
以上是如何在JavaScript中向对象添加属性和方法?的详细内容。更多信息请关注PHP中文网其他相关文章!