Typescript 里面定义属性的时候给我们提供了三种修饰符:
- public:公有,在当前类里面、子类、类外面都可以访问。
- protected:保护类型,在当前类里面、子类里面可以访问,在类外部没法访问。
- private:私有,在当前类里面可以访问,子类、类外部都没法访问。
public
class Person {public name: string; // 公有constructor(name: string) {this.name = name;}run(): void {console.log(`${this.name}在运动`); // 在类里能访问}}let p = new Person("张三");p.run();console.log(p.name); // 在类外面能访问class Child extends Person {constructor(name: string) {super(name);}run(): void {console.log(`${this.name}在运动--子类`); // 子类能访问}}let c = new Child("李四");c.run(); // 李四在运动--子类console.log(c.name); // 在类外面能访问
protected
class Person {protected name: string; // 保护constructor(name: string) {this.name = name;}run(): void {console.log(`${this.name}在运动`); // 在类里能访问}}let p = new Person("张三");p.run();// console.log(p.name); // 报错,在类外面不能访问class Child extends Person {constructor(name: string) {super(name);}run(): void {console.log(`${this.name}在运动--子类`); // 子类能访问}}let c = new Child("李四");c.run(); // 李四在运动--子类// console.log(c.name); // 报错,在类外面不能访问
private
class Person {private name: string; // 私有constructor(name: string) {this.name = name;}run(): void {console.log(`${this.name}在运动`); // 在类里能访问}}let p = new Person("张三");p.run();// console.log(p.name); // 报错,在类外面不能访问class Child extends Person {constructor(name: string) {super(name);}run(): void {// console.log(`${this.name}在运动--子类`); // 报错,子类不能访问}}let c = new Child("李四");c.run(); // 李四在运动--子类// console.log(c.name); // 报错,在类外面不能访问
静态属性和方法
使用 static 修饰符修饰的方法称为静态方法,它们不需要实例化,而是直接通过类来调用,若加上修饰符,和其他属性和方法效果一样。
ES5 中的静态方法、静态属性:
function Person() {this.run1 = function () {}; // 实例方法,实例化后调用}Person.run2 = function () {}; // 静态方法,类名直接调用Person.name = "lucy"; // 静态属性Person.run2(); // 静态方法的调用
TypeScript 中的静态方法、静态属性:
class Person {public name: string;public age: number = 20;static sex = "男"; // 静态属性constructor(name: string) {this.name = name;}run() {console.log(`${this.name}在运动`);}work() {console.log(`${this.name}在工作`);}static print() {console.log("print静态方法" + Person.sex); // 静态方法,没法直接调用类的属性}}var p = new Person("tony");p.work();p.run();Person.sex; // 男Person.print();
抽象类
abstract 用于定义抽象类和其中的抽象方法。
什么是抽象类?
首先,抽象类是不允许被实例化的:
abstract class Animal {public name;public constructor(name) {this.name = name;}public abstract sayHi();}let a = new Animal("tony");

上面的例子中,我们定义了一个抽象类 Animal,并且定义了一个抽象方法 sayHi。在实例化抽象类的时候报错了。
其次,抽象类中的抽象方法必须被子类实现:
abstract class Animal {public name;public constructor(name) {this.name = name;}public abstract sayHi();}class Cat extends Animal {public eat() {console.log(`${this.name} is eating.`);}}let cat = new Cat("Tom");

上面的例子中,我们定义了一个类 Cat 继承了抽象类 Animal,但是没有实现抽象方法 sayHi,所以编译报错了。
正确使用:
abstract class Animal {public name;public constructor(name) {this.name = name;}public abstract sayHi();}class Cat extends Animal {public sayHi() {alert(`Meow, My name is ${this.name}`);}}let cat = new Cat("Tom");cat.sayHi();
