簡體   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