Why embed the JavaScript class in an anonymous function() call?

前端 未结 6 635
北恋
北恋 2021-02-05 10:31

I was reading about the new JavaScript-like language from Microsoft called TypeScript. In the playground (example section), there is a simple class in TypeScript syntax converte

6条回答
  •  爱一瞬间的悲伤
    2021-02-05 10:51

    The following is called an Immediately Invoked Function Expression:

    (function(){ ... })();
    

    It is used to keep the global scope clean. Though, in this case it isn't necessary since the return value is assigned to a variable Greeter. The only time this pattern is useful is when you want "private" static members.

    E.g.:

    var Greeter = (function () {
        var foo = 'foo', bar = 'bar'; /* only accessible from function's defined
                                         in the local scope ... */
    
        function Greeter(message) {
            this.greeting = message;
        }
        Greeter.prototype.greet = function () {
            return "Hello, " + this.greeting;
        };
        return Greeter;
    })();
    

提交回复
热议问题