Closures in auto executing functions vs objects

2020-02-03 07:15发布

问题:

Let us say I have the following:

var foo = (function(){
    var bar = 0;
    return {
       getBar: function(){
           return bar;
       },
       addOne: function(){
           bar++;
       },
       addRandom: function(rand){
           bar += rand;
       }
    }
})();

And I have the following:

var foo2 = function(){
    var bar = 0;
    this.getBar = function(){
           return bar;
       };
    this.addOne = function(){
           bar++;
       };
    this.addRandom = function(rand){
           bar += rand;
       }
};

Is the only difference in executing the functions a new?

alert(foo.getBar()); //0
foo.addOne();
foo.addRandom(32);
alert(foo.getBar()); //33

var foo2_obj = new foo2;
alert(foo2_obj.getBar());//0
foo2_obj.addOne();
foo2_obj.addRandom(32);
alert(foo2_obj.getBar());//33

They both out put the exact same thing.

So what is the difference in the long run?

What can one do that the other cannot?

Fiddle Demo of the above: http://jsfiddle.net/maniator/YtBpe/

回答1:

In the first one you can only create the object once, while with the second one you can create as many objects as you like. I.E. the first one is effectively a singleton.

Note that closures are not ok for the second one. Every time you instantiate it you are creating the functions all over again and waste a ton of memory. The prototype object is intended to counter this, where you can create the functions once outside a function scope and no accidental closures are created.

function foo2(){
    this._bar = 0;
}

foo2.prototype = {

    constructor: foo2,

    getBar: function(){
        return this._bar;
    },

    addOne: function(){
        this._bar++;
    },

    addRandom:function(rand){
        this._bar += rand;
    }

};

Then:

var a = new foo2, b = new foo2, c = new foo2;

Creates three instances which have their own _bar but share the same functionality.

jsperf

You can "compare" all of this to PHP, some of the code won't even run but it's "equivalent" in principle:


var foo = (function(){
    var bar = 0;
    return {
       getBar: function(){
           return bar;
       },
       addOne: function(){
           bar++;
       },
       addRandom: function(rand){
           bar += rand;
       }
    }
})();

is roughly "equivalent" to this in PHP:

$foo = new stdClass;

$foo->bar = 0;

$foo->getBar = function(){
    return $this->bar;
};

$foo->addOne = function(){
    $this->bar++;
}

$foo->addRandom = function($rand){
    $this->bar += $rand;
}

var foo2 = function(){
    var bar = 0;
    this.getBar = function(){
        return bar;
    };
    this.addOne = function(){
        bar++;
    };
    this.addRandom = function(rand){
        bar += rand;
    }
};

Is roughly "equivalent" to this in PHP:

Class foo2 {


    public function __construct(){
    $bar = 0;

        $this->getBar = function(){
            return $bar;
        };
        $this->addOne = function(){
            $bar++;
        };
        $this->addRandom = function($rand){
            $bar += rand;
        };


    }

}

function foo2(){
    this._bar = 0;
}

foo2.prototype = {

    constructor: foo2,

    getBar: function(){
        return this._bar;
    },

    addOne: function(){
        this._bar++;
    },

    addRandom:function(rand){
        this._bar += rand;
    }

};

Is roughly "equivalent" to this in PHP:

Class foo2 {

    public $_bar;

    public function __construct(){
        $this->_bar = 0;    
    }

    public function getBar(){
        return $this->_bar;    
    }

    public function addOne(){
        $this->_bar++
    }

    public function addRandom($rand){
        $this->_bar += $rand;
    }

}

...and is the only one that is close to OOP in the three above examples




回答2:

The only difference is that foo will be a generic Object, whereas foo2_obj will identify as a foo2 when checking its type (i.e. foo2_obj.constructor == foo2 will be true, while the equivalent on foo is foo.constructor == Object).

Of course, there's an important distinction between foo and foo2 - foo is an object, while foo2 is a function (intended for use as a constructor). Thus, it is trivial to make as many instances of foo2 (of which foo2_obj is one), while the idea of creating "instances" of foo doesn't really make sense - the best you could do are copies (which is more difficult than calling a constructor).

Due to the copying/creating instances distinction, the second approach allows for real OO programming with prototype chains, while the first makes such things much more difficult (and ill-advised).



回答3:

[1]first,but not important:efficiency

function Foo1() {
    var bar = 0;
    return {
        getBar: function () {
            return bar;
        }
    }
}
var o = Foo1();
o.getBar();


function Foo2() {
    var bar = 0;
    this.getBar = function () {
        return bar;
    }
}
var o = new Foo2();
o.getBar();

which is the faster?,look object-literal-vs-new-operate

[2]program pattern:the former has no program pattern,but the latter will benefit form prototypal inheritance.if now we want to add a method named "logBar",

former:

1:extend every Foo1 instance:

o.logBar = function () {
    console.log(this.getBar());
}
o.logBar();

bad way!

2:find where Foo1 defined and add:

function Foo1() {
    var bar = 0;
    return {
        getBar: function () {
            return bar;
        },
        logBar:function () {
            console.log(this.getBar());
        }
    }
}
var o = Foo1();
o.logBar = o.logBar();

would you want to go back to do this when you want to add more method ervey time?

latter:

Foo2.prototype.logBar = function () {
    console.log(this.getBar());
}

var o = Foo2();
o.logBar = o.logBar();

this would be work fine.

[3] back to efficiency: in Foo1's way,it product logBar function instance ervey time when a Foo1 instance created.object-literal-vs-new-operate



回答4:

I think in my personal view of this two types
1- Singleton
2- Object

Let's we say we have one page having their javascript using Object (Second), and having many utils using singletons (First), and works fine.

But one day we need a new page that call the first page via AJAX, this new page have their javascript using Object (Second) and have the same utils using singleton, but we add some new functions in the utils singletons.

Turns out, the utils singletons in the new page are overriden for the loaded utils singletons in the first page, So when the new page execute some of those new function doesn't exist, generating errors ...

I think this is my point, the singletons are overriden when you have this scenario, and find erros in cases like this are hard.. hard..., diferent from a object that have unique instances

Cheers.



回答5:

The main difference is actually that foo is an object, whereas foo2 is a function.

That means that you'll not be able to create another object like foo that is not actually foo itself, except if you copy/paste its code.

On the other hand, you can create another foo2 object and manipulate it while using foo2_obj for another purpose.

To make short, foo is an instance while foo2 can bee seen as a class (even if it's just a function constructing an object).

It depends on what you want to do in your program, but I'd surely recommend to use the 2nd form which is allowing to reuse your code by creating other instances.



回答6:

foo and foo2_obj They are the same. In both cases you have a function that creates a new object, references a variable in closure scope and returns that object.

You have 4 things

  • anonymous function that is a factory for "foos"
  • object foo created from anonymous factory
  • foo2 which is a name factory for "foo2_objs"
  • object foo2_obj created from foo2 factory

The exact difference between using new and returning function literals from a function is neglible if you don't touch <Function>.prototype

You probably want to compare

var foo2 = function(){
    var bar = 0;
    this.getBar = function(){
           return bar;
       };
    this.addOne = function(){
           bar++;
       };
    this.addRandom = function(rand){
           bar += rand;
       };
};

To

var Foo = {
  addOne: function () { this.bar++; },
  addRandom: function (x) { this.bar+=x; }
};

var foo3 = function () {
  return Object.create(Foo, { bar: { value: 0 } });
}

foo3 uses prototypical OO. this means you don't have to recreate those functions all the time.



回答7:

In simple terms if you are creating 10 instances of foo and foo2, the getBar function of foo will exists 10 times in memory and that of foo2 will be only once.

Also, modern browsers like chrome with V8 compiler, it compiles the js to machine code... in that case foo2 will get translated to a native class object and its like a 20 times faster (when you create say 1000 instances in a loop)


I normally uses the simple object method when there is only once instance of that class/module is needed. The structure that I follow is,

var myInstance = function(){
   var self = {};
   self.bar = null;
   self.gerBar = function(){
      return self.bar
   }
   return self;
}();

this is quite similar to the foo approach, but I find this structure more handy.


One other difference (in practical use) that i normally encounter is when I have callback functions or timeouts inside the class,

var foo2 = function(){
    this.doSomething = function(){
        var temp = this;
        $.someAsyncCall(function(){
           // 'this' in current scope is the inline function itself, not the class instance
           // so have to store the instance ref in a local var in outer scope and then use that to get the class instance
           temp.callAfterAsyncCall();
        });
    };
    this.callAfterAsyncCall = function(){
    };
};

as you can see the local temp variable is not pretty when you have a lot these cases.

where in the other approach, you always the the self reference everywhere inside the module scope,

var myInstance = function(){
   var self = {};
   self.doSomething = function(){
      $.someAsyncCall(function(){
          self.callAfterAsyncCall();
      });
   }
   self.callAfterAsyncCall = function(){
   };
   return self;
}();

I not sure if its important for you, but just thought worth mentioning.