JavaScript Programming Patterns
klauskomenda.com
klauskomenda.com
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.
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.
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.
<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.
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.htmlthis also allows you to do prototypal inheritance, which is not possible with other "module patterns" - whatever that is, they are just singletons.
return this; 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 var self = this;
but that's bikesheddingwether we should call it thisObj or self :)
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
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")
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.
This sounds pretty dangerous to me. Crockford has this to say http://bit.ly/r9EZO about it.
Now, maybe she was just joshing me... but I'm not taking that chance.
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.
_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.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.
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.