ECMAScript6 class 奇怪的行为

ECMAScript6 class strange behavior

我正在编写一个 ES6 程序,并且从 WebStorm 的输出中得到了非常不正常的行为。有人可以解决这个问题吗 - 我正在使用 Babel 进行转译。

class DateLocationValidator{
    _appointments;
    constructor(appointments){
        this._appointments = appointments;
        console.log(this._appointments);
    }

    validate(appointmentViewModel)
    {
        console.log('validating');

        if(this._appointments==null || this._appointments.length==0) {
            console.log('appointments null');
            console.log(this._appointments);
            return {
                outcome:true,
                reason:'',
                conflictId:0
            };
        }else{

            console.log('appointments not null');
            var result = this._appointments.where(function(appointment)
            {
                console.log('searching');
                if(appointment.startDate==appointmentViewModel.startDate && appointment.startDate==appointmentViewModel.startDate){
                    console.log('found');
                    return true;
                }
            });

            if(result.length>0){
                return {
                        outcome:true,
                        reason:'There is already an appointment scheduled for this location on this date',
                        conflictId:result[0].id
                };
            }
        }
    }
}

这是测试:

it("Fails when appointment clashes exactly",function(){
        try {
            let appointments = [new AppointmentViewModel(1, new Date(2015, 1, 1), new Date(2015, 1, 2))];
            let validator = new DateLocationValidator(appointments);
            let appointmentViewmodel = new AppointmentViewModel(1, new Date(2015, 1, 1), new Date(2015, 1, 2));
            let result = new validator.validate(appointmentViewmodel);
            expect(result.outcome).toBe(false);
        }
        catch(excep){
            console.log(excep)
            expect(true).toBe(false);
        }
    });

'appointments null' 总是输出到控制台。这是在构造函数中正确输出数组之后。

此外,当我尝试从验证调用函数时,出现未定义的错误。

有人能帮忙吗?

干杯 M

出于某种原因,您将 validate 作为构造函数调用。省略 new 关键字!

let result =     validator.validate(appointmentViewmodel);
//           ^^^

在真正的 ES6(未转译)中,这会抛出异常,因为使用方法语法声明的函数不能用 new 调用(它们没有 [[construct]] 槽)。