July 16, 2010
Cleaner Javascript Design
By Briam Rodriguez
Cleaner Javascript Design By Leveraging Closures and the “Function as Object” design pattern
Intro
Javascript is a flexible, object oriented, language which is usually dismissed as a toy language for being too simplistic, or for lacking sufficient features with which to develop applications. Part of this dismissive attitude stems from a misunderstanding of Javascript’s greatest strength, its flexibility.
It’s so flexible in fact, that it leads to spaghetti code more often than not because the developer approaches javascript development without a solid design pattern in mind. Most javascript scripts that I’ve seen (and some of my own, I must admit) have turned out to be horrible tangled messes of asynchronous callbacks (functions which are scheduled to be run at an unspecified future time) to which even more cruft is added as application requirements are added or removed. Essentially, most of these “one-off” scripts contain the same trademark flaw: they fail to model their entities appropriately, leading to inconsistencies all across the board.
There are three solutions to these recurring problems, namely the judicious use of closures, the “Function as Object” design pattern, and the proper modeling of program entities.
Functions As Objects
Many languages have special constructs to define an object, viz. keywords relegated to that specific use. Javascript has no such constructs, though it has the capability to define objects, and it approaches the task in an odd but satisfactory manner.
It turns out that functions (as in most of the better languages) are actually first-class objects themselves. This means that they can be assigned, transferred, have properties added to them dynamically, can (usually) be created anonymously, and can reference themselves (amongst other interesting properties).
We take advantage of the fact that javascript can define anonymous functions inline and use it towards our “Function as Object” pattern through the use of the “new” keyword. The “new” keyword takes the object given after it and creates a reference to a new, separate copy of the defined object.
Let us examine this example (a record for a person), assuming it is in the global scope:
// define a new person object
var Person = new function() {
};
This would create a new object “Person” in the global application namespace, with no properties or methods. Right now this is of no practical use, because the object contains no data (properties), and no operations (methods) can be performed upon it. Before we can assign it properties though, the Person object needs to have a reference to itself.
Speaking of properties, how can we assign any if we do not know where they are to be assigned?
We could use the global name “Person” to assign the object attributes, but what happens if we change the object’s name to “HumanBeing”? That would be out of the question since our references would break, and each would need to be individually changed.
We could use the the “this” keyword which references the current call-chain, but that would break if one of our methods is used as a callback. (This is due to the fact that the meaning of the “this” keyword depends on how a function was called.) Or, we could use something called a closure; and pass a reference around subtly and make our lives easier.
I will opt for the latter.
Closures
You may have heard of the term closure before; but what is it and why is it so useful? A closure is simply a function which encapsulates a reference to its containing environment. Absolutely everything… container, properties, methods. the whole kit is passed along. This in itself is not an exciting thing, but when used carefully it can do some pretty amazing things like assist in generating customized functions, or in our case, encapsulate a reference to our parent object. Let’s see how we can use a closure to provide a consistent access point into our object, independent of caller.
Take a look at the our Person object:
var Person = new function() {
var self = this;
self.first_name = "John";
self.last_name = "Doe";
self.birth_date = "10/24/1900";
// notice the use of anonymous "lambda" functions to assign methods to the object
self.get_full_name = function() {
return(self.first_name + " " + self.last_name);
};
};
What do you see? When we execute the code we get:
js> Person.get_full_name()
John Doe
Properly Modelling Your Entities
Using this design pattern we can model our entities and save time and effort, all while beating more complex languages to the punch!
What we have done is taken the current value of the “this” keyword, and caused a global reference to be passed into all of Person’s methods. This might seem similar to you if you’ve ever programmed Python, for example, where the self keyword is part of all objects and used in exactly the same way. This particular design pattern, of “Function as Object” + closures is something which makes programming in javascript hassle free and makes things work as expected. You can even call Person’s methods in javascript callbacks (from jQuery for example) and as long as you reference self, you will not have any issues as to when the “this” keyword really is “this” or “that” or something totally different altogether!
Consider this example code:
// Notice how I omit the "new" keyword before the function declaration
// in order to create a class definition instead of a class instance.
// The "new" keyword is usually used to create instances of a class
// defined in this way.
var PersonClass = function(first_name, last_name, date_of_birth) {
var self = this;
self.first_name = first_name;
self.last_name = last_name;
self.date_of_birth = date_of_birth;
self.get_full_name = function() {
return(self.first_name + " " + self.last_name);
};
};
var John = new PersonClass("John", "Doe", "10/24/1900");
var Jenny = new PersonClass("Jenny", "Doe", "10/24/1900");
js> John.get_full_name()
John Doe
js> Jenny.get_full_name()
Jenny Doe
It doesn’t matter whether get_full_name is invoked directly or indirectly via callback because the reference to the internal object is passed in via a closure. Now that is object orientation that could rival even the best of OOP languages!
Conclusion
Use of the “Function as Object” design pattern, coupled with usage of the self reference/closure idiom is a powerful tool to make javascript look and feel like the big boys of programming, whilst keeping the simple flexible design of the javascript language available at your fingertips. It removes the inconsistencies encountered when calling methods or accessing parameters via call-back, isolates the way you access data from the way that methods are called (function call chain), encapsulates your data, and is just plain overall fun!
Filed under: Uncategorized — @ 2:00 pm
Comments (0)
Manufacturing Lightning in a Bottle By josh
On Wednesday of this week The Factory Interactive held a seminar Social Media for Small Business to provide some background information on the major players in the social media game and give our attendees some solid tips on how to leverage them. Throughout Jason’s (@jasoninasi) presentation it became more and more clear that one of the most dependable methods for gaining rapid traction in social media is timeliness.
Let’s take a a quick look back at some of the examples presented during the seminar:
Kogi BBQ (@kogibbq) - Kogi uses Twitter to announce the locations for their lunch trucks on a daily basis and while only following 1,700+ users themselves they have amassed a following of their own of almost 68,000 hungry lunch goers!
Kogi, and other daily information providers like Woot (@woot) and Dell (@DellOutlet) are leveraging routine, informative and short-shelf life tweets in order to create urgency in their followers thereby maximizing the value of their tweets.
When we launched the We Want Wade (#wewantwade) campaign in May several factors converged to provide the “perfect storm” of social media. Wade’s contract was ending, anxiety amongst his fans was increasing (would he stay or would he go?) and interest in the NBA was peaking during the playoffs. We were able to successfully leverage these conditions in order to generate a frenzy of interest and participation immediately upon the campaign’s launch.
So, how can the average business owner use this knowledge to gain a leg up on the competition, drive more leads in or gain more followers?
First, you have to remember to keep that signal to noise ratio low. You should always have something worthwhile and on-topic to say. If you don’t have anything to contribute, your silence will be more appreciated than a dry, over-extended sales pitch.
Second, take advantage of the information available at Google Trends. Nothing will grab new audience members or reinforce your relationship with existing followers more than a timely tweet to your recently written blog post covering some breaking news, industry trend or burgeoning meme.
Finally, if the situation is applicable, you can turn short-duration promotions into big money. Consider a regular publishing frequency combined with quickly expiring valuable offers.
Good Luck!
Filed under: Uncategorized — @ 11:41 am
Comments (0)
September 17, 2009
Anheuser-Busch- Getting it in the Can
By jason
It looks like more traditional shops are getting into the viral video game. I came across this online online ad from DDB this morning. The spot with it’s thinly veiled innuendo of anal sex will surely be a hit with the YouTube, college crowd and make it’s way into your inbox soon (sorry..that pun was just way to easy).
However with 80% of the US beer drinking population dominated by males…is this really the best association for the beer? Shouting out “Hey bud, give me one in the can” is sure to turn more than a few heads in a crowded bar.
Filed under: Agency News,Marketing,Media News — Tags: advertising, agency, Anheuser-Busch, social media, viral campaign — @ 11:08 am
Comments (0)
August 13, 2009
Social Media & It’s Affect On Advertising Agencies
By jason
This presentation covers the growth of Social Media and it’s effects on Brands and includes the following:
- What is Social Media
- Why you need to integrate Social Media into your campaigns.
- Examples of successful Social Media campaigns.
- Tips & Tools you can start using today.
Because the numbers are staggering & Media is becoming ubiquitous and your brands, customers and services are being talked about in real time…without you!
Filed under: Marketing,SEO — @ 9:56 am
Comments (0)
August 5, 2009
Why you need Twitter now more than ever.
By Ashley
Here are the Top 10 reasons why your company should be on Twitter…today:
1. Twitter is unstoppable. It’s growth has surprised any expectations, rising to 23 million unique users in July (that’s a 16% growth from May alone and doesn’t include those that use outside resources for Twitter instead of logging on to twitter.com)
2. Twitter is the number one social media tool among Fortune 100 companies. Of the Fortune 100 companies on Twitter, 94 percent use it for news/announcements, 67 percent for customers service, and 57 percent for deals and promotions. It’s just as easy for you to be on Twitter as it is for the big guys!
3. Twitter is still the buzz word. The media is obsessed with it and it recieves TONS of free press and coverage.
4. Twitter is a great way to connect with your customer base for everything from customer service to promotional purposes. Many small business have been able to double their customer base due to Twitter alone.
5. “No time” is no longer a good excuse. There are agencies and tools out there that will manage and update your Twitter page daily.
6. Twitter allows you to immediately notify your customers of promotions, events or even clear up a mishap or customer service issue. Perfect example: JetBlue tweets flight delays (which we all now is probably a full time job on it’s own). You are able to manage the customers expectations.
7. It’s easy! See our earlier post on how to set up & effectively use twitter for business
8. Become an expert in your field. Twitter allows you to post valuable information that your peers and customers will look forward to reading. You’ll become a reliable and trusted source for information, which in turn builds brand credibility.
9. Use Twitter to get to know your customers better. Not only should they follow you, but you should reciprocate the act. You will get some insight in to what your customers want and look for, helping you craft your messages and marketing efforts. Twitter is also great for focus groups and other means of research.
10. Instant gratification. Results are speedy. Gone are the days of watching and waiting. You can tweet promotions and coupons for today. Or tweet questions to your followers and have answers within minutes. Or even put the kabosh on any negativity that may surface… immediately.
This is just the beginning. Twitter will continue to grow by the day and you don’t want to be left out!
Filed under: Marketing,SEO — @ 1:29 pm
Comments (0)Older Posts »
Subscribe to our feed
- September Archives
- August Archives
- June Archives
- May Archives
- April Archives
-
March Archives
Social media...it means business.
A Twitter Experiment
Newspapers want a bailout plan?? Say what??!
TFI takes home GOLD at Caples Awards
Today's Match-Up... Twitter vs. SEO
Newspapers are finally catching on (sorta)
Facebook vs. Google
The Factory Interactive takes home the gold at the 2009 ADDY Awards for Germville Campaign
-
February Archives
Are Newspapers Still Relevant?
Everything can be beautiful - Unexpected Inspired Design
SEOtrack™ - Business Development Solutions For Search and Social Media Marketing.
BumpTop - the desktop re-invented
Fictional Ad Personality wins Twitter's First Annual Shorty Awards:
Out with the old...in with the new.
Inspiration: WordPress Customization Examples
SNL's MacGruber likes his Pepsi.
Crowdsourced Doritos spot dethrones Anheuser-Busch's #1 Ad Meter dynasty.
Peta Super Bowl Ad banned from TV - again !
Super Bowl XLIII Ads fail to deliver social media ROI
- January Archives
- December Archives
- November Archives
- Categories