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 a functional approach and much more suitable for it (for example, encapsulation), and then everything that you see
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.
to bring inheritance to the mix
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.
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 20 '10 at 12:41 2010-09-20 12:41
source share