My response to a question about closures on SO included the following code 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 left a comment on my answer which said:
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 typically create objects using new. But why is it considered not a good practice? It appears that using new and not using new both return the same thing. What is the correct way to create objects from closures?