I want to be able to create an object in Javascript that has public methods which can access the object's private members. However, I've heard that there's overhead in declaring public methods every time an object is created, so I'd prefer to avoid that overhead. So, for example, this code would do what I want:
function createMyObject(parameter) { var that = {}; var privateVariable, privateMethod = function () { return 1; }; that.publicVariable = 0; that.publicMethod = function () { privateVariable = privateMethod(); } return that; } But everytime someone calls createMyObject, it has to create functions to set the public methods. If instead I do this:
function MyClass(parameter) { var privateVariable, privateMethod = function () { return 1; }; this.publicVariable = 0; } MyClass.prototype.publicMethod = function () {}; Here, I can avoid having to create new functions to set public methods everytime an object is constructed, but those public methods can't access the object's private members.
Is there some way to avoid the overhead of having to create new functions for public methods everytime an object is constructed, but also be able to let them have access to private members?