typescript编译小研究

1.继承的实现方式

typescript代码:

class A{
    name: string;

    constructor(name){
        this.name=name;
    }

    print(){
        console.log(this.name);
    }
}

class B extends A{
    old: number;

    constructor(name,old){
        super(name);
        this.old=old;
    }
    
    out(){
        console.log(this.name+this.old);
    }
}

let b=new B('jc',1);
b.out();

用tsc编译后的ES5代码:

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var A = (function () {
    function A(name) {
        this.name = name;
    }
    A.prototype.print = function () {
        console.log(this.name);
    };
    return A;
}());
var B = (function (_super) {
    __extends(B, _super);
    function B(name, old) {
        var _this = _super.call(this, name) || this;
        _this.old = old;
        return _this;
    }
    B.prototype.out = function () {
        console.log(this.name + this.old);
    };
    return B;
}(A));
var b = new B('jc', 1);
b.out();
  • 可以看出来typescript中类型之间的继承是通过寄生组合式继承来完成的,这里可以给出一个寄生组合式继承的简单例子:
function extend(B,A){
    var prototype=Object.create(A.prototype);
    prototype.construtor=B;
    B.prototype=prototype;
}

function A(name){
    this.name=name;
}

A.prototype.print=function(){
    console.log(this.name);
}

A.prototype.num=1;

function B(name,old){
    A.call(this,name);
    this.old=old;
}

extend(B,A);

B.prototype.ready=function(){
    console.log(this.name+this.old);
}

寄生组合式继承的基本思路是:不必为了制定子类型的原型来调用父类型的构造函数,只需要将父类型的原型对象的副本赋给子类型的原型对象,然后修正一下原型对象的构造函数指向。

2.私有变量的实现方式

typescript代码:

class A{
    private name: string;

    constructor(name){
        this.name=name;
    }

    print(){
        this.console();
    }

    private console(){
        console.log(this.name);
    }
}

let a=new A('jc');
a.print();

tsc编译后的代码:

var A = (function () {
    function A(name) {
        this.name = name;
    }
    A.prototype.print = function () {
        this.console();
    };
    A.prototype.console = function () {
        console.log(this.name);
    };
    return A;
}());
var a = new A('jc');
a.print();

可以看到typescript并没有为私有属性和函数做任何处理,但是如果在外部访问了私有变量,在编译时会报错,可见typescript是在编译过程的底层实现了对私有变量的检查。

3.静态变量的实现方式

typescript代码:

class A{
    static num: number=1;
}

console.log(A.num);

tsc编译后的代码:

var A = (function () {
    function A() {
    }
    return A;
}());
A.num = 1;
console.log(A.num);

可见静态变量时与类有关的变量,所以可以直接将该属性赋给构造函数对象,让其成为构造函数的属性,在类的内部也要通过类名才能访问到静态变量。

  1. red

你可能感兴趣的:(typescript编译小研究)