Mike M Mike M - 1 month ago 8
TypeScript Question

Angular 2 component variable scope and references

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.

Answer

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.