访问器
类的访问属性包括 private、public、 protected
。
public:默认;类内外都可以访问
private:类内可访问
protected:类内和继承类可访问
例子
public
class Person {
public name: string
public say(){
console.log(this.name) //类内
}
}
const person1 = new Person()
person1.name = 'mtg' //类外
private
class Person {
private name: string
private say(){
console.log(this.name) //类内
}
}
const person1 = new Person()
person1.name = 'mtg' //类外 报错
protected
class Person {
protected name: string
protected say(){
console.log(this.name) //类内
}
}
class Teacher extends Person {
protected sayBye(){
this.name //继承
}
}
const person1 = new Person()
person1.name = 'mtg' //类外 报错
构造器constructor()
构造函数在被实例化的时候自动执行constructor()
,在实例化时传递传递参数。
class Person {
public name:string
constructor(str:name){
this.name=name
}
}
const Teacher = new Person('mtg')
Teacher.name //mtg
上述构造函数中,需要首先定义name。可以简化上述写法:
class Person {
constructor(public name:string){ }
}
const Teacher = new Person'mtg')
Teacher.name //mtg
当子类继承类,也要构造器时,需要在子类中手动调super()
,通过super
向父类传。
class Person {
constructor(public name:string){ }
}
class Teacher extends Person {
constructor(public age:number){
super('mtg')
}
}
const teacher = new Teacher(18)
teacher.name // mtg
teacher.age //18