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
this
ornew
function 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?