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

前端 未结 6 566
北恋
北恋 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:42

    This is to allow for private members. In this example, all members are public so your two constructions are equivalent. However, if you want to provide for private members you need to hide them from the calling scope via a closure. Thus if you have a private member like so:

    class Greeter {
        private greeting: string;
        constructor (message: string) {
            this.greeting = message;
        }
        greet() {
            return "Hello, " + this.greeting;
        }
    } 
    

    You would probably get something like this:

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

    The greeting variable will be available to any function defined inside the anonymous function, but invisible everywhere else.

提交回复
热议问题