6 ms·
JavaScript Programming Patterns
- monos 17y agoeasiest & most flexible is still this: var myNamespace = {}; myNamespace.foo = function() { var privateFoo = 1; this.publicBar = "test"; var privateFn = function() {}; this.publicFn = function() {}; return this; } // usage myFoo = new myNamespace.foo(); as crockford says & in my experience http://javascript.crockford.com/private.html http://javascript.crockford.com/private.html this also allows you to do prototypal inheritance, which is not possible with other "module patterns" - whatever that is, they are just singletons.
- yannis 17y agoDo you need the return this;
- deleted 17y ago[deleted]
- aarongough 17y agoI agree. For small projects I use the same pattern but in the global namespace. I normally also create an intentional closure when initiating the object, this way I can refer to the parent object regardless of whether it's methods have been copied away or not (like when you assign an object method to an event handler) var testObject = function() { // Make sure the 'this' object is always available // to the object's methods via the 'thisObj' variable var thisObj = this; this.publicVar = "This is a string"; this.alertBox = function() { alert( thisObj.publicVar ); } } object1 = new testObject(); window.onload = object1.alertBox
- monos 17y agoI know what you mean. When I have lots of event-handlers in a prototype I like to assign var self = this; but that's bikeshedding
- aarongough 17y agoWhat do you mean by 'bikeshedding'?
- monos 17y agohttp://catb.org/jargon/html/B/bikeshedding.html http://catb.org/jargon/html/B/bikeshedding.html wether we should call it thisObj or self :)
- aarongough 17y agoAh gotcha. I checked the definition at a few places but the context still seemed unclear. I agree, one way or the other is fine. Do you use 'self' because you're a Ruby coder? That actually the reason I would stay away from it! But then again I'm easily confused :-p
- thegrossman 17y agoI used to live by the "revealing module pattern", although I didn't know that's what it was actually called. Currently, I do something along these lines: var MyObject = function() { var _obj = {} var privateVariable = 'foo' var privateMethod = function(){} _obj.publicVariable = 'bar' _obj.publicMethod = function(){} return _obj }() To me, it makes the separation of public and private methods and variables easier to observe. Also, an unrelated note: I've stopped using semicolons round about 6 months ago and have never looked back. It makes my life simpler, I'm happier, and my sex life has never been better. EDIT: Removed syntax error (the "var" in front of "_obj.whatever")
- yannis 17y agoYou can even get more thrifty by saving on vars as well :) and conserve some more electrons besides those affected by semicolons. _obj.publicVariable = 'bar' _obj.publicMethod = function(){} Personally I cannot type any statement without an ending semicolon, it is a mannerism that stayed with me since I had to learn Pascal. It makes it difficult for me to do anything useful in Python and I am actually contemplating to see a therapist for this.
- thegrossman 17y agoNot only is that more thrifty, but it is necessary. Thanks for catching the typo!
- monos 17y agosorry, but why would carry the extra _obj around? why not simple do it like in my example above?
- thegrossman 17y agoThat works, too! The reason I like using _obj is because "this" is notoriously hard to work with in JS. If, inside foo(), you have an iterator that you pass a function to, "this" takes on a different meaning inside that function. Some people are really good at working out what "this" refers to, but I'm not. So I assign the main object to _obj just to be safe.
- tumult 17y agoWho's voting this up? Did you actually read this drivel? The second solution is dealing with the creation of a singleton, which means creating an object and assigning values (e.g. functions) to its properties. ??? JavaScript is object-based rather than object-oriented. In JavaScript, you just need to call the constructor function of your (custom) object with respective parameters to create an object. You just have objects with properties and methods that you create by calling functions with parameters. This is not object-oriented due to some crazy reason I'm going to make up right now so that JavaScript seems edgy and cool. It's not a stupid language, man, you just don't get it! As stated above, this pattern is not that handy here, but consider a situation when there is some heavy and complex computing involved. You certainly do not want to do that each time the function gets called. Peter calls this kind of function definition a “promise” Yeah that's not a thunk, it's a Design Pattern. Also that's a really stupid way to execute it, bro. I like how this basically works its way through ever more obfuscated "patterns" and arrives at "Revealing Module Pattern" with an incomprehensible tangle of object properties and initialization methods. The first, straightforward way – which he wrote to try to parody as "oldschool" bad style – is the best way to do this here, though he assigns properties on objects needlessly and uses 'this' without a good reason. The rest of the examples are like a joke. Actually, reading this again now, it's pretty hilarious. Maybe I'll vote it up, too.
- bsaunder 17y agoI up voted it. I skimmed it in a few minutes (reading your rant and typing this response took longer). I'm rather fluent in JavaScript so I didn't learn much new, but it seemed like a nice short comparison of some of the mechanisms of using JavaScript. Perfect, and complete, probably not. Useful to someone trying to grasp the basic options available, sure. The "old school" style may be the best way for you, but certainly would cause problems with many developers or while trying to use some large JavaScript libraries (though fortunately most those tend to use some type of encapsulation (except the unfortunately ubiquitous Prototype)). If you don't like JavaScript patterns or the subject doesn't interest you read the link head line and move on. If you are interested, I think the article is a nice brief summary of some ways to use JavaScript.
- kls 17y ago
- figital 17y agoI like that he doesn't call them "design patterns".
- nkohari 17y agoI recently found JS.Class: http://jsclass.jcoglan.com/ http://jsclass.jcoglan.com/ It provides Ruby-style inheritance patterns for Javascript. Initially I was skeptical (most of the other attempts at adding OOP structure to JS have been awful), but it's simplified my code significantly. I've also found that it plays nicely with jQuery, as long as you know when to be functional and when to be object-oriented.
- jerf 17y agoHmm, that "old way" is wrong. The way it would have been done in 1998 is something like <li> <a href="..." onclick="this.style.backgroundColor='#FF6633'">BBC</a> <a href="..." onclick="this.style.backgroundColor='#CCCC00'>NYT</a> and so on. With no further Javascript needed. Except I wouldn't have trusted "style", and the browsers without styles probably wouldn't have been able to change background colors for links at all, but that's obviously not the point here. ... To be honest, this is probably how I'd do it today, too. The natural objection about it being not "semantic" or whatever is something I'd fix in the generation code, where it would be perfectly "semantic". There isn't a single one of those techniques that isn't an amazing pile of code to accomplish something very simple. Yeah, I understand this is for didactic purposes, but I'm finding it hard to see past this point. YMMV.