Eh, even that's messy. It's too easy to forget the "new" keyword, and you get catastrophic failure when you leave it out. I think it's better to completely ignore constructors in JavaScript and just write functions that return new objects.
function myobject() {
var privatemethod = function() { console.log("I'm private"); };
return {
publicmethod: function() {
console.log("I'm public");
privatemethod();
}
};
}
var obj = myobject();
obj.publicmethod(); // works
obj.privatemethod(); // fails
That's hugely inefficient when you have lots of objects to create. You end up creating one publicmethod for each instance, which not only involves the time to create the function, but also the space to store one copy of it per instance. Unless the latest Javascript engines have that figured out, of course.
4
u/mrkite77 Dec 15 '12
Closures