Deathmatch: Self Executing Anonymous Function -vs- “new function”

前端 未结 3 2104
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 08:17

Answer Embedded Below in UPDATE 2/ANSWER

Thanks to Joseph for helping me find the answer (even though I don\'t like it =).

ORIGINAL

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 08:42

    I've seen this and I liked it

    var MyThing = (function(){
    
        function MyThing(args){
        }
    
        MyThing.prototype = {
            prototypeMethod: function() {}
        };
    
        return MyThing;
    })();
    

    You can also do this

    MyThing.create = function(args){
        return new MyThing(args);
    }
    

    Usually it is enclosed in an another self invoking function. In order to avoid naming collisions.

    (function({
    
    })(window);
    

    And the window object is passed as an argument, to assign it to an upper scope.

    window.MyThing = MyThing;
    

    In this example you can use, static variables,private etc.

提交回复
热议问题