1

Is there a way to avoid always having to attach a "this" to referencing private Component variables or functions?

For example, the following will cause a "Cannot find name" error on "foo"

export class SomeComponent {
    private foo = 5;

    someMethod(){
        console.log(foo);
    }
}

To fix, I need to attach a "this" to the foo variable, as in:

console.log(this.foo);

I'm all for strong identification of variables, but this seems overly strict given the smaller size of most Angular components.

1 Answer 1

3

In JavaScript and TypeScript you need to refer to the fields and functions of the class in that class with the this keyword

From The Documentation of TypeScript

Let’s take a look at a simple class-based example:

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

let greeter = new Greeter("world");

The syntax should look familiar if you’ve used C# or Java before. We declare a new class Greeter. This class has three members: a property called greeting, a constructor, and a method greet.

You’ll notice that in the class when we refer to one of the members of the class we prepend this.. This denotes that it’s a member access.

Sign up to request clarification or add additional context in comments.

10 Comments

Constructor shouldn't be considered a class member, isn't it?
it is a class member, but not field. I speak about the fields, and also functions. Constructor is also a function but you can't call it inside the same class with this.
I get that. The problem I have is that I get ridiculous looking code that looks like this.val = this.myMethod(this.variable1, this.variable2). Personal preference I guess. Thanks for clarifying though...
@MikeM I'm with Suren, it's not possible. Typescript has to implement classes this way because of scope isolation issues in javascript, if you don't specify the this.gretting you can accidentally access window.gretting. In coffeescript there's the @gretting prefix that means this.gretting maybe there is a equivalent feature for typescript.
@LenilsondeCastro, thanks, that makes sense. It would be nice if the TypeScript transpileation would assume that locally declared variables and methods were scoped this if referenced internally in the class and other scopes (e.g. window) would require explicit declaration.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.