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?
ES2015 Classes
In the ES2015 specification, you can use the class syntax which is just sugar over the prototype system.
Benefits
The main benefit is that static analysis tools find it easier to target this syntax. It is also easier for others coming from class-based languages to use the language as a polyglot.
Caveats
Be wary of its current limitations. To achieve private properties, one must resort to using Symbols or WeakMaps. In future releases, classes will most likely be expanded to include these missing features.
Support
Browser support isn't very good at the moment (supported by nearly everyone except IE), but you can use these features now with a transpiler like Babel.
Resources
The simple way is:
The reason for
that
is thatthis
can be bound to something else if you give a method as an event handler, so you save the value during instantiation and use it later.Edit: it's definitely not the best way, just a simple way. I'm waiting for good answers too!
Based on the example of Triptych, this might even be simpler:
This only creates a single object instance, but is still useful if you want to encapsulate a bunch of names for variable and methods in a class. Normally there would not be the "Bob, M" arguments to the constructor, for example if the methods would be calls to a system with its own data, such as a database or network.
I am still too new with JS to see why this does not use the
prototype
thing.Following are the ways to create objects in javascript, which I've used so far
Example 1:
Example 2:
Example 3:
Example 4: Actual benefits of Object.create(). please refer [this link]
Example 5 (customised Crockford's Object.create):
To keep answer updated with ES6/ ES2015
A class is defined like this:
I think you should read Douglas Crockford's Prototypal Inheritance in JavaScript and Classical Inheritance in JavaScript.
Examples from his page:
Effect? It will allow you to add methods in more elegant way:
I also recommend his videos: Advanced JavaScript.
You can find more videos on his page: http://javascript.crockford.com/ In John Reisig book you can find many examples from Douglas Crockfor's website.