How to do class implementation?

后端 未结 1 625
轮回少年
轮回少年 2020-12-22 04:17

TypeScript compiles a class something like:

var UrlProvider = (function(){
        //tons of logic in here that only needs to be performed once for each Url         


        
相关标签:
1条回答
  • 2020-12-22 04:39

    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.

    0 讨论(0)
提交回复
热议问题