Javascript:为什么使用匿名函数和返回语句

时间:2018-02-13 19:37:21

标签: javascript

标题并没有真正描述我正在寻找的内容,因此我可以通过示例来展示它。 有什么区别:

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语句,但它给出了完全相同的结果。这是为什么?或者,哪一个是"正确"一个?

3 个答案:

答案 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)

没有被认为是"错误"或"纠正"。他们做了不同的事情。

  • 顶部代码段会创建一个动态计算值的方法,而
  • 底部代码段会预先计算该值,即如果checkAvailabilityrooms发生更改,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)