TypeScript学习41

静态块

在class里面可以定义一个静态块,在里面可以做一些class本身的初始化工作。

class MyClass {
    static x: number = 0;

    static {
        console.log("In static block");
        MyClass.x = MyClass.x + 1;
    }
}

console.log(MyClass.x);


TypeScript学习41

运行结果:

TypeScript学习41

泛型类

泛型也可以用在class上面。

class Box {
    contents: Type;
    constructor(value: Type) {
        this.contents = value;
    }
}

const b = new Box('abc');
console.log(b.contents);


TypeScript学习41

不过类型参数不能用在静态成员上。

class Box {
    static contents: Type;
}


TypeScript学习41


TypeScript学习41

由于TypeScript转换到JavaScript的时候,contents并不会根据不同类型生成多份不同的contents,所以TypeScript干脆就不支持这个特性。


类里面的this

由于TypeScript并不改变JavaScript的运行时行为,所以TypeScript对于this的处理和JavaScript一样。

比如下面的代码:

class MyClass {
    name: string = "MyClass";
    getName() {
        return this.name;
    }
}

const c = new MyClass();
const obj = {
    name: "obj",
    getName: c.getName
};
console.log(obj.getName());


TypeScript学习41

最后输出的结果是:


TypeScript学习41

只是由于在JavaScript里面,this的值,依赖于这个函数是被哪个对象调用的。


之后JavaScript里面推出了箭头函数(Arrow Function)。

class MyClass {
    name: string = "MyClass";
    getName = () => {
        return this.name;
    }
}

const c = new MyClass();
const obj = {
    name: "obj",
    getName: c.getName
};
console.log(obj.getName());


TypeScript学习41

运行结果:

TypeScript学习41

这样做有几个特殊的地方:

1. This的值在运行的时候是能保证的,永远都指向当时创建的时候的对象。

2. 这样会更消耗内存,由于每个实例都会有一份代码的拷贝。

3. 子类是没办法调用super.getName的。因为没有原型链的定义。


使用this参数,可以适当解决使用普通方法的问题。

注意这里的this参数,只是用来控制调用时使用的对象类型。

class MyClass {
    name: string = "MyClass";
    getName(this: MyClass) {
        return this.name;
    }
}

const c = new MyClass();
const d = c.getName
console.log(d());


TypeScript学习41

使用这种方式,可以在编译期检测出问题。

TypeScript学习41

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章