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