//4.1定义类 class Person{ name:string; constructor(n:string){ this.name = n; } getName():string{ return this.name } setName(name:string):void{ this.name = name; } } const p = new Person(‘qin‘); p.setName(‘kai‘); //实现继承 class Web extends Person{ constructor(name:string){ super(name) } } var w = new Web(‘li‘); w.getName() //4.2类里的修饰符(ts定义属性时给我们提供了3种修饰符) // public: 公有, 在类里面,,子类,类外面都可以访问 // protected: 保护类型, 在类里面,子类可以访问,类外部不能访问; // private:私有, 在类里面可以访问,子类和类外面都不能访问; //属性如果不加修饰符,默认为公有 //静态方法与实例方法 // function Person2(){ // this.sum = function(){ //实例方法 // console.log(123) // } // } // Person2.run = function(){ //静态方法 // console.log(234) // } // Person2.name=‘aah‘ //静态属性 // let p2 = new Person2(); // p2.sum(); // Person2.run() class Animal { private name: string; constructor(theName: string) { this.name = theName; } } class Rhino extends Animal { constructor() { super("Rhino"); } } class Employee { private name: string; constructor(theName: string) { this.name = theName; } } let animal = new Animal("Goat"); let rhino = new Rhino(); let employee = new Employee("Bob"); animal = rhino; //animal = employee; // 错误: Animal 与 Employee 不兼容.
原文:https://www.cnblogs.com/kaiqinzhang/p/12894661.html