1

TypeScript compiles a class something like:

var UrlProvider = (function(){
        //tons of logic in here that only needs to be performed once for each UrlProvider instance
        function UrlProvider(baseUrl){
            var baseRequest = {
                get: function(){return baseUrl;},
                update: function(){return baseUrl;},
                delete: function(){return baseUrl;}
            };
            var documents = function(){
                var context = '/documents/';
                return{
                    get: function(){return baseRequest.get() + context;},
                    post: function(){return baseRequest.post() + context;},
                    delete: function(){return baseRequest.delete() + context;}
                }
            };
            var editors = function(){
                var context = '/editors/';
                return{
                    get: function(){ return baseRequest.get() + context; },
                    post: function(){ return baseRequest.post() + context; },
                    delete: function(){ return baseRequest.delete() + context; }
                }
            }
        }
        return UrlProvider;
    })();

Is there any benefit to putting logic outside of the UrlProvider constructor, but inside the closure of the outer IIFE? My thinking was that perhaps if we needed a remote service or some other expensive process to create UrlProviders that could possibly be better placed in the outer closure vs. the constructor of the UrlProvider? Is this correct? IS there any benefit to putting logic in outside the constructor, but inside the IIFE?

Huangism
  • 16,278
  • 7
  • 48
  • 74
wootscootinboogie
  • 8,461
  • 33
  • 112
  • 197

1 Answers1

3

IS there any benefit to putting logic in outside the constructor, but inside the IIFE

Yes. The IIFE is needed for inheritance to capture the base class. This is shown below

class Foo {
    log() { }
}

class Bar extends Foo {
    log() {
        super.log(); // IIFE needed for `super` to work
    }
}

Look at the generated javascript (I've removed the extends function).

var Foo = (function () {
    function Foo() {
    }
    Foo.prototype.log = function () {
    };
    return Foo;
})();

var Bar = (function (_super) {
    __extends(Bar, _super);
    function Bar() {
        _super.apply(this, arguments);
    }
    Bar.prototype.log = function () {
        _super.prototype.log.call(this); // IIFE needed for `super` to work
    };
    return Bar;
})(Foo);

_super is captured by the IIFE. Reason is that functions are the only thing that create a variable scope in JavaScript and that is why we create an IIFE in the codegen to capture the base class in a nice local name (_super). This is conventional JavaScript, not specific to TypeScript.

basarat
  • 261,912
  • 58
  • 460
  • 511