What are the pros and cons of each type/approach in writing Object Oriented scripts?
Personally, I have found closures (functional? approach) as a way to encapsulate state more natural and perhaps more elegant. I, however, have heard that this use of closures is slower in JavaScript implementations.
I would at least like to know where a prototypal approach would be most appropriate.
What is JavaScript? JavaScript (often shortened to JS) is a lightweight, interpreted, object-oriented language with first-class functions, and is best known as the scripting language for Web pages, but it's used in many non-browser environments as well.
Classical inheritance is limited to classes inheriting from other classes. However prototypal inheritance includes not only prototypes inheriting from other prototypes but also objects inheriting from prototypes.
The most important difference between class- and prototype-based inheritance is that a class defines a type which can be instantiated at runtime, whereas a prototype is itself an object instance.
The Prototypal Inheritance is a feature in javascript used to add methods and properties in objects. It is a method by which an object can inherit the properties and methods of another object. Traditionally, in order to get and set the [[Prototype]] of an object, we use Object. getPrototypeOf and Object.
"Functional" Style (most people would call this "traditional OOP"):
Prototype Style:
So if performance isn't a huge issue for you and you're only familiar with traditional OOP ... go for it (Pro Javascript Design Patterns, from APress, has a good pattern for this). But if performance matters or you're worried about the extra layer of abstraction complicating your debugging, take the time to read up on how prototype inheritance works; you'll be a better Javascript programmer for it.
P.S. If you're worried about not having true "private" methods with the prototype style, I strongly recommend reading: http://snook.ca/archives/javascript/no-love-for-module-pattern It provides a great explanation of why true "private" members are actually a bad thing (at least in most JS development environments).
use prototypes to indicate object inheritance. it's pretty involved to duplicate that with functional code (I assume you mean the pattern where you have private members in a closure and return an object that contains your public members?)
function Animal() { }
function Cat () { }
Animal.prototype.sleep = function() { /* blah */ };
Cat.prototype = new Animal;
Cat.prototype.meow = function() { /* blah */ };
var simon = new Cat();
simon.sleep();
simon.meow();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With