class修饰符的使用及区别
public、private、protected、static、abstract
public:可以继承、实例化
class Person { public name: string; constructor(thename: string) { this.name = thename; } } class Jack extends Person { age: number; constructor(name: string, age: number) { super(name) this.age = age; } say() { console.log(`my name is ${this.name}, age ${this.age}`); } } let p1 = new Person('tom'); console.log(p1.name); // tom let j1 = new Jack('jacker', 10); j1.say(); // my name is jacker age 10
private 私有属性只能在基类中访问,不能在实例、派生类中访问
class Person { private name: string; constructor(thename: string) { this.name = thename; } sayname() { console.log(`my name is ${this.name}`); } } class Jack extends Person { age: number; constructor(name: string, age: number) { super(name) this.age = age; } say() { // 只能在Person中访问 // console.log(`my name is ${this.name}, age ${this.age}`); // error } } let p1 = new Person('tom'); p1.sayname(); // tom // console.log(p1.name); // tom // error 只能在Person中访问 let j1 = new Jack('jacker', 10); j1.sayname(); // jacker
protected 受保护的,可以被继承,在派生类中可以访问,子类、父类都不能实例访问
class Person { protected name: string; constructor(thename: string) { this.name = thename; } sayname() { console.log(`my name is ${this.name}`); } } class Jack extends Person { constructor(name: string) { super(name) } say() { // 只能在Person中访问 console.log(`my name is ${this.name}`); } } let p1 = new Person('tom'); p1.sayname(); // tom console.log(p1.name); // tom // error 只能在Person、子类中访问 let j1 = new Jack('jacker'); j1.say(); // jacker console.log(j1.name); // error 只能在Person、子类中访问
// static 只能通过基类、子类访问,实例不能访问
class Person { static myName: string; constructor(name: string) { Person.myName = name; } sayname() { return Person.myName; } } class Jack extends Person { constructor() { super('jacker'); } } let p1 = new Person('tom'); p1.myName; // error Person上不存在myName属性 console.log(p1.sayname());// tom // 在类的外部访问 console.log(Person.myName); // tom let j1 = new Jack(); // 子类实例访问基类方法 console.log(j1.sayname()); // jacker j1.myName // error Jack 上不存在myName属性 // 子类访问静态属性 console.log(Jack.myName); // jacker
// abstract 抽象类中的抽象方法不包含具体实现并且必须在派生类中实现
abstract class Person { sayname() { console.log('my name is sayname'); } // 抽象方法不具体实现 abstract say(): void; } class Jack extends Person { // 子类必须实现父类抽象方法 say() { console.log('my name is jacker'); } } // let p1 = new Person(); // 抽象类不可以被实例化 let j1 = new Jack(); j1.sayname(); j1.say()
class修饰符的使用及区别
public、private、protected、static、abstract
public:可以继承、实例化
private 私有属性只能在基类中访问,不能在实例、派生类中访问
protected 受保护的,可以被继承,在派生类中可以访问,子类、父类都不能实例访问
// static 只能通过基类、子类访问,实例不能访问
// abstract 抽象类中的抽象方法不包含具体实现并且必须在派生类中实现