代码示例:
JS代码:
// Create the template for objects that are hotels
function Hotel(name, rooms, booked) {
this.name = name;
this.rooms = rooms;
this.booked = booked;
this.checkAvailability = function() {
return this.rooms - this.booked;
};
}
// Create two hotel objects
var quayHotel = new Hotel('PD', 80, 8);
var parkHotel = new Hotel('Huang', 120, 99);
// Update the HTML for the page
var details1 = quayHotel.name + ' rooms: ';
details1 += quayHotel.checkAvailability();
var elHotel1 = document.getElementById('hotel1');
elHotel1.textContent = details1;
var details2 = parkHotel.name + ' rooms: ';
details2 += parkHotel.checkAvailability();
var elHotel2 = document.getElementById('hotel2');
elHotel2.textContent = details2;
/*
NOTE: textContent does not work in IE8 or earlier
You can use innerHTML on lines 21 and 26, but note the security issues on p228-231
*/
HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript & jQuery - Chapter 3: Functions, Methods & Objects - Object Constructor</title>
<link rel="stylesheet" href="css/c03.css" />
</head>
<body>
<h1>TravelWorthy</h1>
<div id="info">
<h2>hotel availability</h2>
<div id="hotel1"></div>
<div id="hotel2"></div>
</div>
<script src="js/multiple-objects.js"></script>
</body>
</html>
CSS代码:(参考源码-JavaScript&jQuery交互式前端开发-第3章-函数、方法与对象-使用字面量语法创建对象,http://blog.csdn.net/hpdlzu80100/article/details/52677426 )