0

function declaration:

function F(){
  this.x=1;
}

prototype:

function F(){}
F.prototype.x=1;

prototype inside function declaration:

function F(){ //UPDATE: will throw type error when instantiating. thank you @cookie monster
  this.prototype.x=1;
}

what are the differences if there are any? when does it better to use each way?

Yuval Perelman
  • 4,499
  • 1
  • 22
  • 32
  • BTW, I know a resembling question was asked here: http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript but they discuss function expressions, not declarations – Yuval Perelman Apr 02 '14 at 13:20
  • 3
    You'll almost never see an addition to a function's `.prototype` inside a constructor. And `this` is not a reference to `F` in the first place, so your third example will throw a TypeError. – cookie monster Apr 02 '14 at 13:20

1 Answers1

1

value in prototype will be shared with all instances while the one set in constructor is for each instance independent.

Wrong example

 function F(){}
 F.prototype.x=1;

 a = new F();
 b = new F();

 a.x = 2;
 alert(b.x); //outputs 2 - EDIT: actually 1

EDIT: this is correct:

F = function (){ this.x = {value:1}}

a = new F();
b = new F();

a.x.value = 2;
alert(b.x.value); //outputs 1

//-------------------------------
F = function F(){}
F.prototype.x={value:1};

a = new F();
b = new F();

a.x.value = 2;
alert(b.x.value); //outputs 2

or this:

F = function (){ this.x = 1}

a = new F();

a.x = 2;
delete a.x;
alert(a.x); //outputs undefined (empty string)

F = function F(){}
F.prototype.x=1;

a = new F();

a.x = 2;
delete a.x;
alert(a.x); //outputs 1
Radek Pech
  • 3,032
  • 1
  • 24
  • 29
  • You're right. I tried to make the example as simple as possible and made it so simple it does not work as required anymore. – Radek Pech Apr 02 '14 at 13:46
  • That is a good answer. although the question is about function declarations and you used function expressions, it works either way :) – Yuval Perelman Apr 02 '14 at 13:55