0

I can understand what is the difference in creating and object as a constructor and creating an object in a literal notation and when is better to use each definition, but I can not understand the difference between the following two cases:

function Obj(){
  this.foo = function(){...}
}


function Obj(){}
Obj.prototype.foo = function(){...}

Both are doing the same thing. Both will be instantiated using the same var objNew = new obj();

So what is the difference and when to use each concept?

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • this question has been answered dozens of time before - try searching. – Alnitak Sep 13 '13 at 22:39
  • Object creation using constructor functions and prototype explained here: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 please let me know if you have any questions. – HMR Sep 14 '13 at 04:25

2 Answers2

1

The first one is slower because it gets created every time you call the constructor.

OneOfOne
  • 95,033
  • 20
  • 184
  • 185
  • 1
    and takes more memory. However the _advantage_ of a function declared within the constructor is that such a function can access any other "private" variable declared in the lexical scope of `Obj`. Functions on the prototype can't do that. – Alnitak Sep 13 '13 at 22:39
  • @Alnitak Once you're going to declare private instance specific members in the constructor body you can throw away prototype and have a great head ache trying to clone this object. My advice is because you can't see the future and know how this object is going to change; use `_myprivate` instead. – HMR Sep 14 '13 at 04:28
1

The prototype is shared by all instances. Let us compare:

function Obj(){
  this.foo = function(){...}
}
var o1 = new Obj();
var o2 = new Obj();
console.log(o1.foo === o2.foo); // false

versus

function Obj(){}
Obj.prototype.foo = function(){...}
var o1 = new Obj();
var o2 = new Obj();
console.log(o1.foo === o2.foo); // true

Using a prototype means declaring the prototype properties and functions once, and everyone shares it. A million objects, one foo function.

The "in the constructor" approach creates a local foo function to instances every time you run it. A million objects, a million foo functions each tied its own object.

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153