Pregunta

I'm trying to do some basic stuff in Typescript. I've declared a class like this. Since I want to use the member properties of the class I don't want to use the this keyword in the nameChanged function.

class testController {
        constructor()
        {
        }
        reaction:string = "trist";
        name:string = "erik";
        showReaction:boolean = false;

        nameChanged()
        {
            if(name=="olle")
            {
                this.reaction = "Yippie";
                this.showReaction = true;
            }
            else { this.showReaction = false; }
        }

    }

If I write the row

        this.reaction = "Yippie";

whitout the 'this' keywork I get a compilation error. Could not find symbol 'reaction'. The same thing goes for the showReaction property, but name behaves like expected.

Am I missing something? How can I make reaction and showReaction behave like name?

¿Fue útil?

Solución

Like JavaScript, TypeScript requires the this context to establish "where" to locate functions and properties on objects. Without it, everything would be global (more accurately, it would search the scope chain for the requested variable declaration). And, in TypeScript, the compiler would catch instances where an attempt to use a global variable is made, but not defined.

Unlike some other languages, like C#, there is no default context available within instance methods of a class (an implicit this determined by usage). You need to be explicit and use this when you want to refer to instance methods and properties.

If name works without using this.name, it would imply that there is a global name defined elsewhere, outside of the context of the functions defined on your class. For example it could be like this:

var name: string="global";
class Test {
    name: string;
    public helloName():string {
       return "hello " + name;
    }
}

var t = new Test();
t.name = "instance";

var result = t.helloName();  // result = "hello global"

And if the function body was modified to refer to this.name:

return "hello " + this.name;

The output would be:

var result = t.helloName();  // result = "hello instance"

Otros consejos

Accessing name is not referring to the class member name. you are actually accessing the global name variable.You can only access class members using the this keyword.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top