当前位置:网站首页>Modifiers of attributes of TS public, private, protect

Modifiers of attributes of TS public, private, protect

2022-07-05 20:57:00 qq_ forty-six million three hundred and two thousand two hundre

public Decorated attributes can be accessed and modified anywhere

class Animal{
    
    name: string // Equate to  public name: string; public It's the default modifier  
    age: number

    constructor(name: string, age: number) {
    
        this.name = name
        this.age = age
    }
}

It can also be written as follows :

class Animal{
    
    constructor(public name: string, public age: number) {
    
    }
}

const a = new Animal('tt', 19)
console.log(a);//Animal {name: 'tt', age: 19}

private The decorated attribute is a private attribute , Private attributes can only be accessed and modified inside the class , Its subclasses cannot be accessed and modified ; Its instances are also inaccessible

class Animal{
    
    private name: string 
    private age: number

    constructor(name: string, age: number) {
    
        this.name = name
        this.age = age
    }
}

If you want to visit private Decorated attributes , Can pass set/get

class Animal{
    
    private _name: string 
    private _age: number

    constructor(name: string, age: number) {
    
        this._name = name
        this._age = age
    }

	get age() {
    
		return this._age
	}

	set age(value) {
    
        if(value>=0) {
    
            this._age = value
        }
	}
}

const a = new Animal('aa', 15)
console.log(a.age);//15
a.age = -33
console.log(a.age);//15
a.age = 19
console.log(a.age);//19

protect Protected properties , Only in the current class , And its subclasses , But none of their instances can be accessed

class Animal{
    
    protected _name: string 
    protected _age: number

    constructor(name: string, age: number) {
    
        this._name = name
        this._age = age
    }
}

class Dog extends Animal{
    
    test() {
    
        console.log(this._age);
    }
}

const dog = new Dog(' Little black ', 18)
dog.test()//18
原网站

版权声明
本文为[qq_ forty-six million three hundred and two thousand two hundre]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207052044063808.html