同一页面上的两个相似对象

Two similar objects on the same page

我正在阅读 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();

我完全理解这一点。

然后它告诉我'If you had two objects on the same page, you would create each one using the same notation but store them in variables with different names.'

我试图在 JSFiddel 中创建它,但似乎失败了,我不确定为什么。任何人都可以 post 举个简单的例子和​​解释。那真的很有帮助。

编辑::我不确定它是在告诉我我会完全写另一个对象还是在现有对象中放置一些变量 link 到 name/rooms 等..

提前致谢。

参考:John Duckett - JavaScript 和 JQuery

您可以将其用作 class,因此您可以通过键入 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>

好吧,您可以存储结构相同但值不同的对象。让我通过将您的示例对象包装到一个函数中来解释这一点,该函数可以抽出具有相同结构的不同酒店

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());

还有一个示例,通过 es6-类 使用您的酒店和不同的实例:

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);