Are there any differences in functionality between these two JavaScript module patterns?
var MODULE = (function() {
var privvy = "I'm private!";
return {
getPublic: function() {
return "I'm public";
},
getPriv: function() {
return privvy;
}
};
}());
and
var MODULE = (function() {
var privvy = "I'm private!";
return new function() {
this.getPublic = function() {
return "I'm public";
};
this.getPriv = function() {
return privvy;
};
};
}());
I think what is happening is, in the first, an object with two public members is explicitly declared and then returned. One of the members has a function as a value which has a reference to the ‘private’ variable (i.e. a closure is formed by the immediately-executed function but the getPublic() method still has access to this variable after this function finished execution – I think)
In the second, an object is created by way of an anonymous constructor which assigns two functions to publicly accessible variables and the IEF creates the closure that limits access to the priv variable in the same way.
Do these two variations result in exactly the same object?
The two versions are ever-so-slightly different. For reference I’ve added simple examples of the basic formats (Version A & Version B). There’s not a significant difference in functionality, however Version B adds an additional layer of scope:
Additionally, the prototype of the object returned in Version A will be
Object.prototype, whereas in Version B the prototype will be the anonymous function’s prototype.This difference can be seen by checking the module’s
__proto__property againstObject.prototype.Version A is essentially shorthand for:
Version B is essentially shorthand for:
Version A
Version B