的擴展@KindUser的答案是:你不使用任何地方封在這個類來存儲一些個人狀態
。因此,您應該將方法附加到原型而不是實例本身。它更經濟,因爲現在所有實例共享一個功能,而不是每個實例。 JS引擎可以更好地優化。
然後,你必須在checkAvailability
另一個錯誤:numRooms
需要,因爲它是this
實例的屬性加以解決爲this.numRooms
,並沒有與這個名字的變量。
還有一個關於風格。如果您有類似
if(condition){
return true;
}else{
return false;
}
可以簡化這:
return condition;
//or if you want to enforce a Boolean value,
//but your condition may return only a truthy/falsy value:
return Boolean(condition);
//sometimes also written as:
return !!(condition);
下一步。堅持編碼標準。在JS中,以大寫字母開頭的變量/屬性將指示類/構造函數,因此HotelName
,HiltonHotel
,WeiHotel
是誤導性的。
而我發現屬性名稱hotelName
冗餘和反直覺。伊莫你有一個Hotel
,它有一個name
,但這只是一個意見。
var firstName = 'Steven';
var lastName = 'Curry';
var fullName = firstName + ' ' + lastName;
function Hotel(name) {
this.name = name;
this.numRooms = 20;
this.numGuests;
}
Hotel.prototype.checkAvailability = function() {
return this.numRooms !== 20;
}
Hotel.prototype.getHotelName = function() {
return this.name;
}
var hotel = new Hotel('Hilton');
var hName = document.getElementById('hotelName');
hName.textContent = hotel.getHotelName(); // refer to the `weiHotel` variable
var el = document.getElementById('name');
el.textContent = fullName;
<div id='greeting'> Hello
<span id="name">friend</span>!
<h1>Welcome To the <span id='hotelName'>Hyatt</span></h1>
</div>
或作爲ES6類(和一些圍繞彈唱):
class Person{
constructor(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
//this is a getter, you can read it like a property
get fullName(){
return this.firstName + " " + this.lastName;
}
//this function is implicitely called whenever you try to convert
//an instance of `Person` into a string.
toString(){
return this.fullName;
}
}
class Hotel{
constructor(name) {
this.name = name;
this.numRooms = 20;
this.numGuests;
}
checkAvailability() {
return this.numRooms !== 20;
}
getHotelName() {
return this.name;
}
}
var steve = new Person('Steven', 'Curry');
var hotel = new Hotel('Hilton');
var hName = document.getElementById('hotelName');
hName.textContent = hotel.getHotelName(); // refer to the `weiHotel` variable
var el = document.getElementById('name');
el.textContent = steve.fullName;
//this uses the `toString()` method to convert the `Person` steve into a string
//for people, this makes sense, for the Hotel you'd want to think:
// - where do I want to use this?
// - and what should this string contain?
console.log("Hello, I'm " + steve + " and I'm at the "+ hotel.name);
<div id='greeting'> Hello
<span id="name">friend</span>!
<h1>Welcome To the <span id='hotelName'>Hyatt</span></h1>
</div>
'this.checkAvailability {'是無效的語法。你應該從簡單的東西開始。 – Ryan
你必須從實例訪問該屬性! 'HiltonHotel.getHotelName()'等等。另外你的'checkAvailability'方法(它具有無效的語法)是沒有意義的。如果有20個房間,那麼它仍然可用...請在這裏詢問之前檢查控制檯是否有錯誤 – Li357
將來,請具體說明。 *「不起作用」*沒有告訴我們很多。你會得到一個錯誤,如果是這樣,錯誤是什麼意思?有什麼事情發生? –