标题并没有真正描述我正在寻找的内容,因此我可以通过示例来展示它。 有什么区别:
function Hotel(rooms, booked){
this.rooms = rooms;
this.booked = books;
this.checkAvailability = function(){
return this.rooms - this.booked;
};
}
而且:
function Hotel(rooms, booked){
this.rooms = rooms;
this.booked = booked;
this.checkAvailability = this.rooms - this.booked;
};
}
在我的第二个例子中,我没有使用匿名函数和return语句,但它给出了完全相同的结果。这是为什么?或者,哪一个是"正确"一个?
答案 0 :(得分:1)
在这里你正在初始化而没有别的。 checkAvailability
的状态永远不会改变。
function Hotel(rooms, booked){
this.rooms = rooms;
this.booked = booked;
this.checkAvailability = this.rooms - this.booked;
}
var hotel = new Hotel(2, 1);
hotel.rooms = 1;
console.log(hotel.checkAvailability); // See?, regardless of assigning a new value, the result is 2 - 1 = 1

在这里,您正在使用将计算checkAvailability
。
function Hotel(rooms, booked){
this.rooms = rooms;
this.booked = booked;
this.checkAvailability = function(){
return this.rooms - this.booked;
};
}
var hotel = new Hotel(2, 1);
hotel.rooms = 1;
console.log(hotel.checkAvailability()); // See?, now it was calculated with the new value, the result is 1 - 1 = 0

答案 1 :(得分:-1)
没有被认为是"错误"或"纠正"。他们做了不同的事情。
checkAvailability
或rooms
发生更改,booked
将不会更新以匹配该值。然而,在正常情况下,您可能希望这样做:
class Hotel {
constructor(rooms, booked) {
this.rooms = rooms;
this.booked = books;
}
checkAvailability() {
return this.rooms - this.booked;
}
}
这可以避免创建相同功能的多个副本。
答案 2 :(得分:-1)
第一个是正确的。 第二个示例的checkAvailability只有在房间和预订不变的情况下才会成立。
例如:
function Hotel(rooms, booked){
this.rooms = rooms;
this.booked = booked;
this.checkAvailability = function(){
return this.rooms - this.booked;
};
}
function NonUpdatingHotel(rooms, booked){
this.rooms = rooms;
this.booked = booked;
this.checkAvailability = this.rooms - this.booked;
}
hotel = new Hotel(4, 3)
console.log(hotel.checkAvailability())
hotel.booked = 2
console.log(hotel.checkAvailability())
hotel = new NonUpdatingHotel(4, 3)
console.log(hotel.checkAvailability)
hotel.booked = 2
console.log(hotel.checkAvailability)