Hacker News new | past | comments | ask | show | jobs | submit login
JavaScript Programming Patterns (klauskomenda.com)
48 points by ZLOB-o-ZLOB on Oct 6, 2009 | hide | past | favorite | 28 comments



Who'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.


I 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.


While I think you are coming down a little harsh on the guy, I do have to agree. I am still trying to figure out how that code is enforcing a singleton pattern.

Further, why is everyone still reinventing this stuff. This has all been solved and is in almost every framework.

Take for example my personal favorite, Dojo I would wrap all of this functionality up into a widget that an HTML developer (or myself) could just use a tag to implement e.g

<a href="..." dojoType="my.namespace.BackgroundChangeHREF" newColor="#CCCC00">a link</a>

then the Dojo JavaScript object associated with the widget would have a routine that connects to the onclick event to do the following:

dojo.style("backgroundColor", this.newColor);

That's it, I never code it again. I understand if you are doing this a personal enrichment, but if you are doing this to complete a job task, you should really leverage existing code, this includes code that you and others have already written.


Hmm, 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.


easiest & 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

this also allows you to do prototypal inheritance, which is not possible with other "module patterns" - whatever that is, they are just singletons.


I 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


I 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


What do you mean by 'bikeshedding'?


http://catb.org/jargon/html/B/bikeshedding.html

wether we should call it thisObj or self :)


Ah 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


Do you need the

    return this;


I 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")


>> 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.

This sounds pretty dangerous to me. Crockford has this to say http://bit.ly/r9EZO about it.


That example isn't very reasonable. Obviously, one would expect semicolons to be inserted after lines that form complete statements. It's not hard to ensure that intermediate lines don't do that. It's done for other languages that don't use semicolons.


My mom always told me that I had a limited supply of semicolons in my semicolon bucket, and to not waste them on languages where they aren't strictly required.

Now, maybe she was just joshing me... but I'm not taking that chance.


Leaving them out leads to horrible ambiguity and potential issues. Up to you though :)


I haven't had a single issue in the 6 months of daily Javascriptin' since I've stopped using them.

As I mentioned in another thread, I don't minify my application code so maybe it's not as important as it is for other people.


You 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.


Not only is that more thrifty, but it is necessary. Thanks for catching the typo!


sorry, but why would carry the extra _obj around? why not simple do it like in my example above?


That 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.


nice... except for the semicolons... i guess you're not minifying your code afterwards?


I tend to use minified libraries (JQuery, effects libraries, etc), but unminified application-specific code. Been burned too many times having to root out some obscure error on the live server, and not being able to do so because of minification.

However, I've never had a problem in the cases where I have indeed minified unsemicoloned code. Has anyone else, or is the problem just theoretical? If others have encountered an actual problem, I might have to rethink this strategy for larger codebases.


I've been burned several times by missing semicolons when minifying my code. Now I make sure they're always there. I'm also running everything through JSLint.


I think JSLint can be a big help, especially with semicolons so I made a quick jQuery plugin to run things through it on page load. So I know exactly when something may be wrong.

http://github.com/ejschmitt/AutoLint


I'm using the Javascript Tools bundle for TextMate. It runs JSLint every time I save a javascript file.

http://github.com/subtleGradient/javascript-tools.tmbundle


I recently found JS.Class:

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.


I like that he doesn't call them "design patterns".




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: