为什么TypeScript混合模块和原型模式? [英] Why does TypeScript mix the module and prototype pattern?

查看:208
本文介绍了为什么TypeScript混合模块和原型模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个页面上看看由TypeScript生成的JS代码:

I was having a look at the JS code generated by TypeScript on this page:

http://www.typescriptlang.org/Playground/

基本上,要创建一个 Greeter 类,它输出:

Basically, to create a Greeter class, it outputs this:

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();

var greeter = new Greeter("world");

所以我想知道为什么他们混合模块和原型模式?不会是一样的只是做:

So I'm wondering why they are mixing the module and prototype pattern? Wouldn't it be the same just to do:

function Greeter(message) {
    this.greeting = message;
}

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

var greeter = new Greeter("world");

推荐答案

这里的模块模式的使用是创建一个闭包,允许更多的控制任何封闭的变量(没有泄漏到全局,没有全局污染),并允许创建私有变量只存在通过模块模式的闭包)。

The use of module pattern here is to create a closure, allowing for more control over any closed over variables (nothing leaking into global, no global pollution), and allowing for the creation of 'private' variables (variables that only exist via the module pattern's closure).

这篇关于为什么TypeScript混合模块和原型模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆