繁体   English   中英

ECMAScript6类的异常行为

[英]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”始终输出到控制台。 这是在构造函数中正确输出数组之后。

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

有人可以帮忙吗?

干杯

由于某些原因,您将validate称为构造函数。 忽略该new关键字!

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

在实际的ES6(未编译)中,这将引发异常,因为使用方法语法声明的函数无法使用new调用(它们没有[[construct]]插槽)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM