为什么这个由Typescript生成的JavaScript构造函数包装了一个立即调用的函数?

uet*_*oyo 2 javascript typescript

有人可以向我解释这个'构造函数'定义的优点是什么:

var Tree = (function () {
  function Tree(name) {
    this.name = name;
  }
  return Tree;
})();
Run Code Online (Sandbox Code Playgroud)

代替

var Tree = function(name) {
   this.name = name;
};
Run Code Online (Sandbox Code Playgroud)

第一个变体由TypeScript编译器生成.

Rya*_*ugh 6

在TypeScript的情况下,还有用于捕获基类的额外闭包

class Animal {
    public run() {
        console.log('running!');
    }
}

class Giraffe extends Animal {
    public run() {
        super.run();
        console.log('... and looking awkward');
    }
}
Run Code Online (Sandbox Code Playgroud)

发出:

var Animal = (function () {
    function Animal() {
    }
    Animal.prototype.run = function () {
        console.log('running!');
    };
    return Animal;
})();

var Giraffe = (function (_super) {
    __extends(Giraffe, _super);
    function Giraffe() {
        _super.apply(this, arguments);
    }
    Giraffe.prototype.run = function () {
        _super.prototype.run.call(this);
        console.log('... and looking awkward');
    };
    return Giraffe;
})(Animal);
Run Code Online (Sandbox Code Playgroud)

注意使用通过传递给立即调用函数_super.prototype的参数(Animal此处)来引用基类.没有额外的闭包,在没有污染全局命名空间的情况下,无处可以保存该值.


dan*_*cic 5

在这个具体的例子中,没有差异.如果要在范围内保留一些变量,可能会有差异:

var Tree = (function () {
  var greeting = "Hello ";
  function Tree(name) {
    this.firstname = greeting + name;
  }
  return Tree;
})();
Run Code Online (Sandbox Code Playgroud)

此外,在这种情况下,无法修改greeting变量(事实上,它是私有的).