我正在通过JavaScript书籍工作,目前正在寻找使用Literal Notation创建对象。
我得到了这段代码:
var hotel = {
name: 'Quay',
rooms: 40,
booked:25,
checkAvailability: function() {
return this.rooms - this.booked;
}
}
var hotelName = document.getElementById('hotel-name');
hotelName.textContent = hotel.name;
var freeRooms = document.getElementById('free-rooms');
freeRooms.textContent = hotel.checkAvailability();
我完全理解这一点。
然后告诉我'如果你在同一页面上有两个对象,你可以使用相同的表示法创建每个对象,但将它们存储在具有不同名称的变量中。'
我试图在JSFiddel中创建它,但似乎失败了,我不知道为什么。任何人都可以发布一个快速的例子和解释。这真的很有帮助。
编辑::我不确定它是否告诉我,我会编写另一个对象,或者将一些变量放在链接到名称/房间等的现有对象中。
提前致谢。
参考:John Duckett - JavaScript和JQuery
答案 0 :(得分:2)
您可以将其用作类,因此您可以通过键入new Hotel(name, rooms, booked)
function Hotel(name, rooms, booked) {
this.name = name;
this.rooms = rooms;
this.booked = booked;
}
Hotel.prototype = {
checkAvailability: function() {
return this.rooms - this.booked;
}
}
var hotel = new Hotel('Quay', 40, 25);
var hotel2 = new Hotel('Hotel2', 50, 45);
var hotelName = document.getElementById('hotel-name-1');
hotelName.textContent = hotel.name;
var freeRooms = document.getElementById('free-rooms-1');
freeRooms.textContent = hotel.checkAvailability();
var hotelName = document.getElementById('hotel-name-2');
hotelName.textContent = hotel2.name;
var freeRooms = document.getElementById('free-rooms-2');
freeRooms.textContent = hotel2.checkAvailability();
<div id='hotel-name-1'></div>
<div id='free-rooms-1'></div>
<br>
<div id='hotel-name-2'></div>
<div id='free-rooms-2'></div>
答案 1 :(得分:1)
好吧,您可以存储结构相同但值不同的对象。让我通过将您的示例对象包装到一个具有相同结构的不同酒店的函数中来解释这一点
function hotel(name, rooms, booked) {
var hotel = {
name: name,
rooms: rooms,
booked: booked,
checkAvailability: checkAvailability
};
return hotel;
}
//lets seperate the checkAvailability function from the function so it can be reused.
function checkAvailability() {
return this.rooms - this.booked;
}
var hotel1 = hotel("quay", 40, 25);
var hotel2 = hotel("Ocean View", 50, 20);
console.log(hotel1);
console.log(hotel2);
console.log(hotel1.checkAvailability());
console.log(hotel2.checkAvailability());
&#13;
答案 2 :(得分:0)
还有一个例子通过es6-classes使用不同实例的酒店:
class Hotel {
constructor(name, rooms, booked) {
this.name = name;
this.rooms = rooms;
this.booked = booked;
}
get checkAvailability() {
return this.rooms - this.booked;
}
}
const hotelOne = new Hotel('First', 44, 21),
hotelTwo = new Hotel('Second', 21, 5);
console.log(hotelOne.checkAvailability);
console.log(hotelTwo.checkAvailability);