A while ago, a former classmate and current colleague of me phunehehe had a chance to work with a web app project that makes use of JS-OOP heavily. He was freaked out due to JS syntax and its way to do OOP. Yes, there are certain difficulties when moving from traditional OOP (Java, C#, etc...), but once you know the tips, it isnt something indigestible any longer :)
Basically, Javascript does not support a real class but it does allow you to create an object via a function. That special function is called constructor. With the keyword new, JavaScript makes the function become a constructor and instantiate a new object with the members defined by that function. Inside a constructor, the keyword this references the new object that's being created. It is also a convention that the name of the constructor is capitalized.
And nice enough, you can easily extend the function set of all objects created by a contructor using the prototype attribute.
How about a function that defined in both constructor function and constructor prototype? In that case the one that is defined constructor function will be used.
And from Douglas Crockford (Javascript: the good parts), we can easily implement inheritance with the combination of constructor function and prototype!
Finally, Singleton would be a good open to enclose this small talk about JS OOP. In short, Singleton is a class that has no public constructor but a special function that will return an instance of the class (and create one if the instance doesnt exist) Given Javascript nature, Singleton isnt a class, it also shouldnt be an object as any object in javascript can be created easily from a constructor. In fact, a Javascript's singleton is used as a namespace to provide a level of isolation from the global namespace and therefore served as a single point access to functions. A simple Singleton would look like this
With a bit of Javascript's famous closure, we can make the simpleSingleton to another level of complexity with private variables and functions.
My only question for this is that whether singleton in Javascript is really useful, I havent found any demonstrative sample yet. Comment below if you have any and want to share
No comments:
Post a Comment