简体   繁体   中英

Typescript: Static method return value

I have such class:

export class GlobalValidation {
    static emailPattern(control: AbstractControl): ValidationResult {
        var EMAIL_REGEXP = Pattern.EMAIL;
        return this.checkPattern(control, EMAIL_REGEXP);
    }

    static urlPattern(control: AbstractControl): ValidationResult {
        var URL_REGEXP = Pattern.URL;
        return this.checkPattern(control, URL_REGEXP);
    }

    static checkPattern(control: AbstractControl, pattern: any) {
        if (control.value != "" && !pattern.test(control.value)) {
            return {"incorrectPatternFormat": true};
        }

        return null;
    }
}

EXCEPTION: Uncaught (in promise): Error: Error in :0:0 caused by: Cannot read property 'checkPattern' of undefined TypeError: Cannot read property 'checkPattern' of undefined at GlobalValidation.urlPattern

What am I doing wrong?

When I rewrite class to this:

export class GlobalValidation {

    static emailPattern(control: AbstractControl): ValidationResult {

        var EMAIL_REGEXP = Pattern.EMAIL;

        if (control.value != "" && !URL_REGEXP.test(control.value)) {
            return {"incorrectPatternFormat": true};
        }

        return null;
    }


    static urlPattern(control: AbstractControl): ValidationResult {

        var URL_REGEXP = Pattern.URL;

        if (control.value != "" && !URL_REGEXP.test(control.value)) {
            return {"incorrectPatternFormat": true};
        }

        return null;
    }
}

Everything is fine.

Seems that something is obvious, but I miss it.

You are calling checkPattern using this , albeit it being a static method. Call checkPattern using GlobalValidation.checkPattern(...)

You can't access this from static method. Using static classes has one purpose and that is - you don't need to create a new instance of the class to use the method.

You should use GlobalValidation.checkPatter(...) as Phil Cap suggested or just rewrite it, so it doesn't use the properties of GlobalValidation class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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