2009年5月2日 星期六

JavaScript Programming Patterns

JavaScript Programming Patterns

The Old-School Way
working example




singleton
working example




Module Pattern
working example






Revealing Module Pattern
working example






Custom Objects
working example

Using prototype, we can now add additional properties to the object “blueprint” so that these items are available for every instance of that object right from the start. I ended up with having 3 properties, namely: config, changeColor and init.

呼叫用法也不同




Lazy Function Definition
his pattern is particularly useful when you need to do computations on the page once and then reuse the output multiple times.
working example


用法

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”, which means the outer declaration can be viewed as some kind of promise that later on this function will get redeclared to provide something more useful.




Conclusion

There is no general solution on how such problems should be approached. For a task like this, I believe that the singleton pattern is the most convenient way of doing it. Mostly because less lines of code are required. But for other, more complex problems, using the module pattern or creating custom objects or the lazy function definition might be more appropriate.

沒有留言: