Tân
Tân

Reputation: 1

Do we have to use "this" keyword in typescript?

I'm writing a small example to validate Name, Email, Password and ConfirmPassword via typescript.

I've tried:

interface IValidation {
    CheckingNameAndEmail(): boolean;
    CheckingPasswordAndConfirmPassword(): boolean;
}

class Validation implements IValidation {
    private Input: string;
    private Type: string;

    constructor(input: string, _type: string) {
        this.Input = input;
        this.Type = _type;
    }

    Validate = function () {
        switch (this.Type) {
            case 'Name':
            case 'Email':
                return this.CheckingNameAndEmail()
            case 'Password':
            case 'ConfirmPassword':
                return this.CheckingPasswordAndConfirmPassword()
        }
    };

    CheckingNameAndEmail = function () {
        var reg = this.Type == 'Name'
            ? new RegExp('^.{4,16}$')
            : new RegExp('^((([0-9]?)[a-zA-Z0-9]([0-9]?))+[\._-]??[a-zA-Z0-9]+)+@{1}?([a-zA-Z0-9]+[\._-]??[a-zA-Z0-9]+)+\.(com|net|org|vn){1}$')
        return reg.test(this.Input)
    };

    CheckingPasswordAndConfirmPassword = function () {
        var reg = new RegExp('^.{6,50}$');
        return reg.test(this.Input)
    };
}

As you can see, I must use this keyword in the example. If not, it will throw me error (Like: Cannot find ...).

So my question is: How to avoid calling this multiple times in typescript?

Upvotes: 5

Views: 2530

Answers (2)

MartyIX
MartyIX

Reputation: 28648

You can't avoid it. It's a property of the language.

<hard-learned-lesson>I tend to avoid these kind of shortcuts when I write my code because it makes it harder for others to read it. Readability is a key thing when you target to write good code (for yourself and for others).</hard-learned-lesson>

Upvotes: 6

hansmaad
hansmaad

Reputation: 18905

You have to explicitly write this in Typesript. Sometimes it might be usefull to use an additional local variable to save typing and to write minification friendly code. Consider this example:

foo() {
    if (this.someAwesomeMember.bar) {
        var f = this.someAwesomeMember.bar(123);
        var b = this.someAwesomeMember.bar(321);
        // do more stuff with this awesome member
    }
}

Since we're referencing the awesome member using this all the time, there is not much to minify here. We can do better:

foo() {
    var someAwesomeMember = this.someAwesomeMember;
    if (someAwesomeMember.bar) {
        var f = someAwesomeMember.bar(123);
        var b = someAwesomeMember.bar(321);
        // do more stuff with this awesome member
    }
}

Which can be minified to something like

var a=this.someAwesomeMember;if(a.bar){var f=a.bar(123);var b=a.bar(321);}

Note, that it might decrease readability to replace this by another local variable. So you have to judge carefully here.

Upvotes: 6

Related Questions