The default type modifiers are public
private
class Animal { private name: string public constructor(name) { this.name = name } // public move(distance: number){ // console.log(`${this.name} is move ${distance} m`) // } } class Rhino extends Animal { constructor(){ super('Rhino') } } class Employee { private name: string constructor(name: string){ this.name = name } } let animal = new Animal('Goat') let rhino = New new Rhino () the let empolyerr = new new the Employee ( 'Bob' ) animal = rhino // This is possible because the rhino is a subclass of animal, the animal rhino shared private member // animal // = empolyerr error, because the name two class members are private
protected
class Person { protected name:string constructor(name: string) { this.name = name } } class Employee extends Person { private department: string constructor(name: string, department: string){ super(name) this.department = department } getElevatorPitch(){ return `Hello, my name is ${this.name} and i work in ${this.department}` } } let howard = new Employee('Howard','北京') console.log(howard.getElevatorPitch())// the Hello, My name IS Howard and i Work in Beijing // console.log (howard.name) // error, name property protected, only in class 'Person' and its subclasses access
Now we give constructor Person class with protected
class Person { protected name:string protected constructor(name: string) { this.name = name } } class Employee extends Person { private department: string constructor(name: string, department: string){ super(name) this.department = department } getElevatorPitch(){ return `Hello, my name is ${this.name} and i work in ${this.department}` } } let howard = new Employee('Howard','北京') let person = new new the Person ( 'john') // error, Person class is protected and can only be accessed in the class declaration
readonly
Can be accessed externally, can not be modified externally
{the Person class Readonly name: String constructor (name: String) { the this .name = name } } the let John = new new the Person ( 'John' ) john.name // access // john.name = '' // given, Can not be modified
// above may be written as (attribute parameters), but write code logic is not clear, the recommended way to write class the Person { constructor (Readonly name: String) { the this .name = name } }
2019-05-24 17:39:00