简体   繁体   English

打字稿:静态方法返回值

[英]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 例外:未捕获(承诺):错误:0:0中的错误,原因是:无法读取未定义Type的属性'checkPattern'错误:无法读取GlobalValidation.urlPattern上未定义的属性'checkPattern'

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. 您正在使用this调用checkPattern ,尽管它是静态方法。 Call checkPattern using GlobalValidation.checkPattern(...) 使用GlobalValidation.checkPattern(...)调用checkPattern

You can't access this from static method. 您不能从静态方法访问this方法。 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. 您应该按照Phil Cap的建议使用GlobalValidation.checkPatter(...)或直接重写它,这样它就不会使用GlobalValidation类的属性。

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

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