
JavaScript Programming Patterns - ZLOB-o-ZLOB
http://www.klauskomenda.com/code/javascript-programming-patterns/
======
tumult
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.

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

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

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

~~~
aarongough
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

~~~
monos
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

~~~
aarongough
What do you mean by 'bikeshedding'?

~~~
monos
<http://catb.org/jargon/html/B/bikeshedding.html>

wether we should call it thisObj or self :)

~~~
aarongough
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

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

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

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

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

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

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

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

