ES6的class与TS的class

ES6语法

    class Person{
        a(){
            alert(123)
        };
        b(){
            return 112233
        };
        constructor(aa=999){
            this.x=aa;
            this.bb=function(){
                alert(222)
            }
        };
    }
var p=new Person(1);
则x和bb是p的属性,而a和b在p的原型链上

ES7语法

允许直接在类里面定义属性,允许通过static定义静态属性

class Animal {
  name = 'Jack';
  static num = 42;
  constructor() {
    // ...
  }
}
  
let a = new Animal();
console.log(a.name); // Jack
console.log(Animal.num); // 42
class Doit{
    static hello:number=12321;
    showHello(){
        console.log(Doit.hello)
    }
}
console.log(Doit.hello)
var doit=new Doit()
doit.showHello()

静态属性作为该类本身而非实例的属性被调用。在class内与class外都可以被调用

TS语法

    class Person{
        x:number;
        bb;
        a(){
            alert(123)
        };
        b(){
            return 112233
        };
        constructor(public aa:number=999){
            this.x=aa;
            this.bb=function(){
                alert(222)
            }
        };
    }
var p=new Person(1);
此时constructor中的x和bb必须事先被声明,且默认为public
形参aa默认为private
为private的无法在外部被使用,仅有为public的才能作为实例p的属性被调用

TS中类的继承

class Me extends Person{
    p2p:any;
    constructor(b){
        super(b);
        this.p2p='666'
    };
    mover(){
        console.log('my mover','mover')
        // super.mover()
    }
}
var me:Person=new Me(66)

出现同名的属性和方法则以子类的为准,但是依然可以用 super.对应名的方式调用父类的内容
在子类的构造函数中用super()可以直接继承父类的构造函数

TS的修饰符

对于带有private的, 如果其中一个类型里包含一个private成员,那么只有当另外一个类型中也存在这样一个private成员, 并且它们是来自同一处声明时,我们才认为这两个类型是兼容的。 对于protected成员也使用这个规则。
例如:

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; // Error: Animal and Employee are not compatible
  • private:属性和方法只能在该class部使用,被继承后在子类的constructor中虽然能用super()获取,但无法输出,也无法在方法中使用。因此可以认为private的属性只是为了给该class自身(不包括子)的方法提供参数,与其他都无关系
  • protected:属性和方法虽然也不能在class外调用,可以被子class继承
    同理,加了protected的构造函数,本身无法被实例化。但是继承其class的子类可以实例化
  • readonly:只读属性关键字

修饰符可以出现在构造函数参数中,等同于类中定义该属性同时给该属性赋值:

class Animal {
  // public readonly name: string;
  public constructor(public readonly name) {
    // this.name = name;
  }
}
abstract

用于定义抽象类和其中的抽象方法。
抽象类不能被实例化。
抽象方法不能有实际内容,且必须被子类实现。

abstract class Animal {
  public name;
  public constructor(name) {
    this.name = name;
  }
  public abstract sayHi();
}

class Cat extends Animal {
  public sayHi() {
    console.log(`Meow, My name is ${this.name}`);
  }
}

let cat = new Cat('Tom');
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容