i answered one question about closures here in SO with this sample:
function Constructor() {
var privateProperty = 'private';
var privateMethod = function(){
alert('called from public method');
};
return {
publicProperty: 'im public',
publicMethod: function(){
alert('called from public method');
},
getter: privateMethod
}
}
var myObj = new Constructor();
//public
var pubProp = myObj.publicProperty;
myObj.publicMethod();
myObj.getter();
//private - will cause errors
myObj.privateProperty
myObj.privateMethod
a user commented on my answer saying:
Also, if your function explicitly returns an object it is not a good practice to call it with new because that is misleading – if using new you’d expect the result to be an instance of Constructor
i usually create objects using new. but why is it not a good practice? it seems like using new and not using new returns the same thing. what is the proper way of creating objects from closures?
No, it’s not the same thing. Consider when using
instanceof:Here’s a demo.
So instead, create them by assigning to
this, possibly with a safeguard to prevent forgottennews.Even better, use the prototype when possible: