本文介绍了为什么TypeScript在IIFE中打包一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是TypeScript类:

Here is a TypeScript class:

class Greeter {
    public static what(): string {
        return "Greater";
    }

    public subject: string;

    constructor(subject: string) {
        this.subject = subject;
    }

    public greet(): string {
        return "Hello, " + this.subject;
    }
}

当TS指向ES5时,将其转换为IIFE:

It is transpiled to IIFE when TS targets ES5:

var Greeter = /** @class */ (function () {
    function Greeter(subject) {
        this.subject = subject;
    }
    Greeter.what = function () {
        return "Greater";
    };
    Greeter.prototype.greet = function () {
        return "Hello, " + this.subject;
    };
    return Greeter;
}());

但是,通常作为构造函数呈现时,其工作方式相同。当然,其中的内容看起来更像JavaScript和手写内容:)

However, it generally works in the same way when it is presented as a constructor function. Which, of course, looks more JavaScriptish and handwritten :)

function Greeter(subject) {
    this.subject = subject;
}
Greeter.what = function () {
    return "Greater";
};
Greeter.prototype.greet = function () {
    return "Hello, " + this.subject;
};

用法:

两个代码块以相同的方式工作:

Both blocks of code work in the same way:

Greater.what();  // -> "Greater"
var greater = new Greater("World!");
greater.greet(); // -> "Hello, World!

将其包装在IIFE中有什么好处或动机?

What is the benefit or motives to pack it in IIFE?

我做了一个幼稚的基准测试:

I made a naive benchmark:

console.time("Greeter");
for(let i = 0; i < 100000000; i++) {
    new Greeter("world" + i);
}
console.timeEnd("Greeter");

它显示出几乎相同的实例化速度,当然,我们不能指望任何区别,因为IIFE

It showed virtually the same instantiation speed. Of course, we cannot expect any difference, because the IIFE is resolved only once.

我本以为也许是因为闭包,但是IIFE并没有争论,也不能是闭包。

I was thinking that maybe it is because of closure, but the IIFE doesn't take arguments. It must not be a closure.

推荐答案

在类之间存在继承的情况下,TypeScript将参数传递给IIFE。例如,当<$ c时使用下面的闭包$ c> Greeter 扩展了 BaseGreeter 类:

TypeScript will pass arguments to the IIFE in cases where there is inheritance between classes. For example, the closure below is used when Greeter extends a BaseGreeter class:

var Greeter = /** @class */ (function (_super) {
    // __extends is added by the TS transpiler to simulate inheritance
    __extends(Greeter, _super);
    function Greeter(subject) {
        var _this = _super.call(this) || this;
        _this.subject = subject;
        return _this;
    }
    Greeter.What = function () {
        return "Greater";
    };
    Greeter.prototype.greet = function () {
        return "Hello, " + this.subject;
    };
    return Greeter;
}(BaseGreeter));

这篇关于为什么TypeScript在IIFE中打包一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 04:03