I prefer to use OOP in large scale projects like the one I'm working on right now. I need to create several classes in JavaScript but, if I'm not mistaken, there are at least a couple of ways to go about doing that. What would be the syntax and why would it be done in that way?
I would like to avoid using third-party libraries - at least at first.
Looking for other answers, I found the article Object-Oriented Programming with JavaScript, Part I: Inheritance - Doc JavaScript that discusses object-oriented programming in JavaScript. Is there a better way to do inheritance?
I prefer to use Daniel X. Moore's
{SUPER: SYSTEM}
. This is a discipline that provides benefits such as true instance variables, trait based inheritance, class hierarchies and configuration options. The example below illustrates the use of true instance variables, which I believe is the biggest advantage. If you don't need instance variables and are happy with only public or private variables then there are probably simpler systems.Wow, that's not really very useful on it's own, but take a look at adding a subclass:
Another advantage is the ability to have modules and trait based inheritance.
An example of having the person class include the bindable module.
Disclosure: I am Daniel X. Moore and this is my
{SUPER: SYSTEM}
. It is the best way to define a class in JavaScript.If you're going for simple, you can avoid the "new" keyword entirely and just use factory methods. I prefer this, sometimes, because I like using JSON to create objects.
I'm not sure what the performance hit is for large objects, though.
Thats the way TypeScript compiles class with constructor to JavaScript.
You probably want to create a type by using the Folding Pattern:
That code will give you a type called myType. It will have internal private fields called toggle and text. It will also have these exposed members: the fields count and numbers; the properties toggle, text and numberLength; the methods incrementNumbersByCount and tweak.
The Folding Pattern is fully detailed here: Javascript Folding Pattern
JavaScript is object-oriented, but it's radically different than other OOP languages like Java, C# or C++. Don't try to understand it like that. Throw that old knowledge out and start anew. JavaScript needs a different thinking.
I'd suggest to get a good manual or something on the subject.
I myself found ExtJS Tutorials the best for me, although I haven't used the framework before or after reading it. But it does give a good explanation about what is what in JavaScript world.Sorry, it seems that that content has been removed. Here's a link to archive.org copy instead. Works today. :PObject Based Classes with Inheritence
Simple, sweet, and gets 'er done.