14

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 with new (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 or new

    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?

4
  • Douglas Crawford already talks about the different approaches (primarily in regard to data-hiding).
    – user166390
    Jun 1, 2011 at 3:29
  • 1
    I just created a performance test using jsperf.com: Object definition techniques comparing the three techniques (for fairness; I used my version of prototypes which actually works -- see my answer). This just does a speed test, and the prototype one comes out way faster, as expected. Unfortunately, it doesn't show the memory usage, which I think the prototype one also would be much better at.
    – mgiuca
    Jun 1, 2011 at 3:48
  • Damn, I was hoping that going to the effort of building a performance test would at least earn one upvote on my answer, but hey.
    – mgiuca
    Jun 3, 2011 at 7:59
  • @mgiuca, there, upvoted. I think it's because we didn't connect the comment to your answer (didn't pay attention to the name)
    – Tesserex
    Jun 3, 2011 at 12:40

5 Answers 5

14

Use the prototype. Returning specific objects from constructors makes them non-constructors, and assigning methods to this makes 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:

  • It’s not a real constructor. Adding something to its prototype won’t change the returned objects, new or no new. new Foo() instanceof Foo would also result in false.

Using prototype

Pros:

  • 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 of new ParentConstructor(), then call ParentConstructor from within Constructor. 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 constructor

Pros:

  • You can use closures and therefore private member variables.

Cons:

  • No duck typing; you can’t call a method right off of the prototype with any old object. For example, Array.prototype.slice.call(collectionLikeObject).
8
  • In #1, when you say "constructor's private variables" you mean the instance's private variables.
    – RobG
    Jun 1, 2011 at 3:29
  • @RobG: No, they're really the constructor's private variables, simply used in closures. There is no such thing as a class-level private variable in JavaScript. And I'm really not sure what you mean by your second sentence. When you return an object literal in a constructor, new or not, it is an object... but it's more explicit to call it an object literal because after all they all return objects. Only one way, however, uses return with an object literal, which is what I meant.
    – Ry-
    Jun 1, 2011 at 3:32
  • They are created when the constructor function is called, and kept by a closure from the instance. But each instance has a separate constructor function to create it and closure to that separate function instance, so the privacy belongs to the instance (else they wouldn't be private). Misread the object literal thing, you answered out of order. But still better to just say an object is returned. An object literal is a term for an expression that creates an object, not the object itself. e.g. var a = {a:'a'}; — a is an object, the expression on the RHS is an object literal.
    – RobG
    Jun 1, 2011 at 3:37
  • I guess strictly, a is assigned a reference to the object created when the object literal (expression) is evaluated.
    – RobG
    Jun 1, 2011 at 3:39
  • @RobG: Sorry about the out-of-order thing... I read bottom-to-top. The privacy does belong to the instance but they are still the constructor's. After all, if you have this function: function(){var x=0;return [function(){x++;},function(){return x;}];} then how can it be an instance variable of both functions at once, if one can modify and the other can view? They belong to the constructor still, just a particular invocation of it.
    – Ry-
    Jun 1, 2011 at 3:40
4

It's mostly a matter of preference. There's no one way to make Chicken Noodle soup, and uniform objects are the same way.

I don't use any of those 3, although they all work for their own purposes. I use a custom function called Object:deploy, and use it like this..

var a = { hey: 'hello' },
    b = {}.deploy(a);

console.log(b.hey); // 'hello'

Using prototype is the best for most people because of automatic trickling.

function A() {};
A.prototype.hello = "Hey";

var a = new A();
console.log(a.hello); // 'Hey'

A.prototype.hello = "Hello";

console.log(a.hello); // 'Hello'

And contrary to popular belief, you can use private variables in prototype.

function Hello() {};

(function () {
    var greeting = "Hello";

    Hello.prototype.greet = function () { return greeting };
}).apply(this);

But even though that's possible, it's usually better to do..

function Hello() {};
Hello.prototype.greeting = "Hello";
Hello.prototype.greet = function () { return this.greeting };
4
  • 3
    var dinner = "Chicken Noodle Soup";
    – Shaz
    Jun 1, 2011 at 3:25
  • In the prototype example, the .apply(this) part is unnecessary, it doesn't do anything and can be replaced with an empty call operator (). The anonymous function is called in a global scope, its this is already the global object. And anyway, its this isn't used for anything.
    – RobG
    Jun 1, 2011 at 4:45
  • @RobG My answer, my coding style.
    – McKayla
    Jun 1, 2011 at 4:46
  • @RobG It actually is necessary if you want to use this. In the answer, I don't, but in most cases where wrapping is necessary you do.
    – McKayla
    Jun 14, 2011 at 8:25
2

Well the second approach (prototype) is more similar to standard classes in other languages like Python, in that you have a common "prototype" object which all instances are sharing. To compare the first and second approaches:

  • In approach 1, every time you call "new Foo()", you are creating a brand new object and inserting all the methods. This isn't very time or space efficient, since each Foo instance will have its own table of all the methods. You can test this by creating two Foo objects, and asking foo1.add == foo2.add (false). Approach 3 is very similar to this; I'm not sure what the semantic difference (if any) there is between approaches 1 and 3.
  • In approach 2, you have set up a shared prototype object containing all the methods. If you ask foo1.add == foo2.add, you get true. This is more space- and time-efficient. It also lets you add more methods to the prototype after creating instances, and they will see the new methods.

The problem with approach 2, as you say, is that you can't access the private members. But you can still add non-private members to the object itself, and access those using the prototype methods:

function Foo() {
    this.private = 3;
}
Foo.prototype.add = function(bar) { return this.private + bar }

A caveat is that foo.private is visible externally.

3
  • I suppose a large number of people would say that the external visibility and verbosity of the code is worth it for the additional power of prototypes?
    – Tesserex
    Jun 1, 2011 at 3:36
  • I like @tylermwashburn's use of closures with prototype; that solves the private variable problem.
    – mgiuca
    Jun 1, 2011 at 3:36
  • @Tesserex: Well I would prefer approach 2. Not so much for the power of prototypes (I don't particularly often modify methods after defining a class), but just to avoid the space overhead. It's quite a significant difference. For example, consider a "vector" class with 3 fields and 20 methods. If you have 1000 vectors in your program, approach 1 and 3 will have 23 pointers each (23,000 pointers), whereas approach 2 will have 3 pointers each (3,000 pointers).
    – mgiuca
    Jun 1, 2011 at 3:38
1

The prototype one doesn't have a per object instance overhead only a per class overhead for the add function. This alone is the reason why I don't like the other two approaches.

0

Do not forget about inheritance. Some day you'll need. And for organizing inheritance the best approach is combined technic:

function Foo() {
    this.array = [1, 2, 3];
    this.add = function(bar) { return private + bar; }
}

Foo.prototype.add = function(bar) {  }

var myFoo = new Foo();

Setting fields in constructor is useful to avoid modifying them by children objects. Setting methods to prototype is faster then doing this every time in constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.