4

There are two ways of creating an object in javascript:

  1. use new on a "constructor function"
  2. return a dictionary {} and set the proper key/value pairs

The first is, for example

FooType = function() {
    this.hello = function() { alert("hello"); };
};

foo = new FooType();
foo.hello();

the second is

fooFactory = function() {
    return { 
        hello : function() { alert("hello"); }
    };
};

foo = fooFactory();
foo.hello();

(Code written for the post. not guaranteed correct)

Apart from risks of mistakes of having this bound to the global object, are these two method totally equivalent (also considering prototype inheritance etc...)?

Stefano Borini
  • 138,652
  • 96
  • 297
  • 431

2 Answers2

6

They're not equivalent, especially when considering prototype inheritance.

FooType = function() {
    this.hello = function() { alert("hello"); };
};

var foo = new FooType();

FooType.prototype.bye = function() { alert('bye!'); };

foo.bye(); // "bye!"

The only way you could achieve that in the fooFactory way would be to add it to the object prototype which is a Very Bad Idea.

The first method is much more meaningful in my opinion (since the object has a type you can check against) and can offer much better performance if the prototype is done properly. In your first example, every time you instantiate a new FooType object, it create a new "hello" function. If you have lots of these objects, that's a lot of wasted memory.

Consider using this instead:

function FooType() { }
FooType.prototype.hello = function() {
    alert('Hello');
};
nickf
  • 537,072
  • 198
  • 649
  • 721
2

In example one, foo inherits from FooType's prototype (which hasn't had any changes). foo instanceof FooType is true in the example. In example two, there's no inheritance. If you are going to be reusing methods, use example one but define shared methods on FooType.prototype, not in the function body:

var FooType = function() {};
FooType.prototype.hello = function() { alert("hello"); };
Eli Grey
  • 35,104
  • 14
  • 75
  • 93