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

前端 未结 3 2100
佛祖请我去吃肉
佛祖请我去吃肉 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:25

    For one thing, this pattern:

    MyNamespace.UsingNew = new function() {
        var fnPrivate = function() {
    
            //what's this in here?
    
            return "secrets1";
        };
    
        this.property = "value1";
        this.method = function() {
    
            //what's this in here?
    
            return "property = " + this.property + ' ' + fnPrivate();
        }
    };
    
    • uses the "new" keyword to create an instance of an object, which is modeled using a constructor function. forgetting to use "new", you'll end up named making a function MyNamespace.UsingNew() instead of an object.

    • it's a constructor function, and not yet an object's instance (until you build it using new). you need to use "this" to pertain the object that it will become. it just add's problems to scope, especially when you nest more functions in it, and the value of "this" will change from time to time (and you won't see it coming until the console tell's you). familiar with the self=this or that=this to save the value of "this"? it's pretty much seen when using this pattern

    on the otherhand, the next pattern is somewhat better (for me) since:

    • you don't need to use "new" since it returns an object.

    • not using "this" since it already returns an object. you don't even need "this".

    also, i prefer constructing the other pattern this way:

    ns.myobj = (function(){
    
        //private
        var _privateProp = '';
        var _privateMeth = function(){};
    
        //public
        var publicProp = '';
        var publicMeth = function(){};
    
        //expose public
        return {
            prop:publicProp,
            meth:publicMeth
        };
    }());
    

提交回复
热议问题