Modifiers public, private and protected and the difference

 

TypeScript can use three access modifiers (Access Modifiers), they are public, private and protected.

  • public property or modified method is public and can be accessed from anywhere, all the default properties and methods are public
  • private property or modified method is private and can not be accessed in a statement outside of its class
  • protected or modified property is protected, private, and it is similar except that it is allowed in a subclass to be accessed

Here are some examples:

class Animal {
  public name;
  public constructor(name) {
    this.name = name;
  }
}
 
let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';
console.log(a.name); // Tom

 

In the above example, name is set to public, so that direct access to the instance name attribute is permissible.

Many times, we hope that some properties are not directly accessible, this time we can use the private:

class Animal {
  private name;
  public constructor(name) {
    this.name = name;
  }
}
 
let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';
 
// index.ts(9,13): error TS2341: Property 'name' is private and only accessible within class 'Animal'.
// index.ts(10,1): error TS2341: Property 'name' is private and only accessible within class 'Animal'.

 

Note that, after the code compilation TypeScript, not restricted private property externally accessible.

The above examples are compiled code:

var Animal = (function () {
    function Animal(name) {
        this.name = name;
    }
    return Animal;
}());
var a = new Animal('Jack');
console.log(a.name);
a.name = 'Tom';

 

The use of private property or modified methods in the subclass is not allowed access:

class Animal {
  private name;
  public constructor(name) {
    this.name = name;
  }
}
 
class Cat extends Animal {
  constructor(name) {
    super(name);
    console.log(this.name);
  }
}
 
// index.ts(11,17): error TS2341: Property 'name' is private and only accessible within class 'Animal'.

 

 



And if it is modified by the protected, access is granted in a subclass:

class Animal {
  protected name;
  public constructor(name) {
    this.name = name;
  }
}
 
class Cat extends Animal {
  constructor(name) {
    super(name);
    console.log(this.name);
  }
}

 

 

Guess you like

Origin www.cnblogs.com/flxy-1028/p/10959711.html