What are the basic ways of defining reusable objects in Javascript? I say reusable to exclude singleton techniques, such as declaring a variable with object literal notation directly. I saw somewhere that Crockford defines four such ways in his book(s) but I would rather not have to buy a book for this short bit of information.
Here are the ways I’m familiar with:
-
Using
this, and constructing withnew(I think this is called classical?)function Foo() { var private = 3; this.add = function(bar) { return private + bar; } } var myFoo = new Foo(); -
Using prototypes, which is similar
function Foo() { var private = 3; } Foo.prototype.add = function(bar) { /* can't access private, correct? */ } -
Returning a literal, not using
thisornewfunction Foo() { var private = 3; var add = function(bar) { return private + bar; } return { add: add }; } var myFoo = Foo();
I can think of relatively minor variations on these that probably don’t matter in any significant way. What styles am I missing? More importantly, what are the pros and cons of each? Is there a recommended one to stick to, or is it a matter of preference and a holy war?
Use the prototype. Returning specific objects from constructors makes them non-constructors, and assigning methods to
thismakes inheritance less convenient.Returning an object literal
Pros:
If a person forgets
new, they still get the object.You can create truly private variables, since all methods of the object defined inside the constructor share its scope.
Cons:
newor nonew.new Foo() instanceof Foowould also result infalse.Using
prototypePros:
You leave the constructor uncluttered.
This is the standard way of doing things in JavaScript, and all built-in constructors put their methods on their prototypes.
Inheritance becomes easier and more correct; you can (and should) use
Object.create(ParentConstructor.prototype)instead ofnew ParentConstructor(), then callParentConstructorfrom withinConstructor. If you want to override a method, you’re able to do it on the prototype.You can “modify” objects after they’ve already been created.
You can extend the prototypes of constructors you don’t have access to.
Cons:
It can get to be a bit too verbose, and if you want to change the function’s name, you have to change all of the functions added to the prototype, too. (Either that or define the prototype as one big object literal with a compatible property descriptor for
constructor.)They don’t share an instance-specific scope, so you can’t really have private variables.
Assigning to
this.*in the constructorPros:
Cons:
Array.prototype.slice.call(collectionLikeObject).