简体   繁体   中英

Why 'this' is not allowed on the left side of assignment

In the component class i have been writing this:

export class myapp{
  detail;

  myarr = ['me', 'myself', 'i'];
  title = this.myarr[0];
  this.detail = this.title ;  //error
}

why this.detail is not allowed but this.title is allowed, why I have to create new variable, cant I use variable already in the class

Inside a class but outside of methods you can only initialize fields or declare methods. You can't add arbitrary statements there.

You can use the constructor() for that

export class myapp{
  detail : string = 'I am';

  myarr = ['me', 'myself', 'i'];
  title = this.myarr[0];
  constructor() {
    this.detail = this.title ;  
  }
}

In your instance, there is no point re-declaring the class member...

export class myapp{
    myarr = ['me', 'myself', 'i'];
    title = this.myarr[0];
    detail = this.title ;
}

Why is TypeScript doing this?

TypeScript is helping you to spot that you may have accidentally declared a second member with the same name by stopping you from doing what you are attempting.

You will also note that you don't need to use the this prefix for members in a class. The generated JavaScript will have them...

var myapp = (function () {
    function myapp() {
        this.myarr = ['me', 'myself', 'i'];
        this.title = this.myarr[0];
        this.detail = this.title;
    }
    return myapp;
}());

You can prefix the members with an access modifier. They are private by default.

export class myapp{
    private myarr = ['me', 'myself', 'i'];
    protected title = this.myarr[0];
    public detail = this.title ;
}

Access modifiers are enforced at compile time only.

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