The one thing I don’t like about javascript is that there are hundreds of ways to do things. What I want to know, is how do I declare a class? Do I use the function() approach? Do I call Class.create()? What is ‘standard practice’? What is ‘standard practice’ to declare member functions? Do I use a prototype? Do I use myClass.method()? And lastly, how do I do basic parent-child inheritance? The reason I am asking is because on the internet I have received many ways to do these things. I want to know what is ‘standard practice’.
Share
The reason there is no “standard practice” for declaring classes and particularly subclasses in Javascript is that Javascript doesn’t actually have built-in syntactical language support for the typical classes one would find in C++. Instead, it has it’s own bag of tricks for how you generate similar functionality and there are lots of different ways to express those tricks. There really is no standard way.
I find it best to use one of the more common javascript libraries (jQuery, Prototype, YUI, Closure, etc…) and then use the functions they provide for sub-classing which will give you your own “standard” way of doing it. If you don’t want to use one of the libraries, they you’ll need to borrow some code for sub-classing (the equivalent of YUI’s extend() function) from somewhere and then decide what style you want to use.
I personally think it’s a weakness of Javascript in larger projects, projects with multiple people working on them or projects meant to be extended by others that there’s no language syntax for “the way” to declare classes and sub-classes. Instead, the only way to have a consistent code-base is to decide upon your own what style of declaration you’re going to use and then enforce that as a coding standard in the project, much as one would do with brace style or indent style.