function foo() { var bar = function() { console.log("i'm a private method"); return 1; }; var iAmAPrivateVariable = 1; return { publicMethod: function() { alert(iAmAPrivateVariable); }, publicVariable: bar() } }
This is called a functional appoach since you are actually using locks for encapsulation (which is the only way to do this in javascript).
In general, you should not do OO in javascript, it is not such a big language for it for many reasons. Think of a diagram with short-angle brackets and half-columns, and you will start writing a language like professionals. In this case, once OO is better suited. In such cases the above is usually the best choice.
EDIT: mix inheritance
function parent() { return { parentVariable: 2 }; } function foo() { var bar = function() { console.log("i'm a private method"); return 1; }; var iAmAPrivateVariable = 1; me = parent(); me.publicMethod = function() { alert(iAmAPrivateVariable); }; me.publicVariable = bar(); return me; }
This makes things a little more complicated, but achieves the desired end result, but at the same time uses a functional approach to OO concepts (in this case, using decorator functions instead of real inheritance). What I like about the whole approach is that we continue to view objects as they are intended to be in that language - a bag of property to which you can attach material as you wish.
EDIT2:
Just wanted to give credit, this approach is a very easy simplification to what doug crockford offers in Javascript: The Good Parts. If you want to take your js skills to the next level, I would really like to start there. I don’t think I learned so much from such a small book.
One more note: this is wildly different from what you will see most of the time on most tasks that you will ever work on, and it is often very difficult to explain a) what is happening, and b) why it is a good idea for colleagues.
Matt Briggs Sep 16 '10 at 0:40 2010-09-16 00:40
source share