简体   繁体   中英

Angular2, Typescript - class variables and usage of “this”

I would like to know if I have to use the "this" keyword every single time when referencing an instance-variable. Coming from Java I am used to use "this" only when there is another variable with the same name from another scope (eg. this.arg = arg). But in all the tutorials for Typescript it seems people use "this" every time when an instance-variable (public studentName:string;) is referenced. So if I need to work in a simple method with no arguments of the same name, I seriously need to do:

let nameOfTheStudent=this.studentName;

first if I don't want to write confusing "this" all the time?

Yes, if you want to access a class field, you have to use this.field . That's a really short and boring answer, though, so here's some context.

An important thing to bear in mind about JavaScript/TypeScript classes is that they are just syntax sugar for the existing prototype-based object system. For example, these two pieces of code are functionally equivalent:

// ===== Class syntax =====

class MyClass {
    myField: string;

    constructor() {
        this.myField = "Hello, world!";
    }

    myMethod() {
        return this.myField;
    }
}

let myInstance = new MyClass();

// ===== Prototype syntax =====

function MyClass() {
    this.myField = "Hello, world!";
}

MyClass.prototype.myMethod = function() {
    return this.myField;
};

let myInstance = new MyClass();

In fact, if you look at the JavaScript generated by the TypeScript compiler, the latter example is probably what you'll see (give or take). So in reality, though you may make use of class fields in your code, JavaScript doesn't really have any concept of them - you're just getting and setting properties on a constructor function.

Rather than making classes have different syntactical rules to normal functions, the spec was designed to keep the mapping as consistent with the existing rules as possible, and keep the class syntax minimal. This is why you have to specify this , unlike in Java or C#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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