is there a difference between assigning a property in function declaration and assigning it with prototype in JS?

StackOverflow https://stackoverflow.com/questions/22812436

  •  26-06-2023
  •  | 
  •  

Domanda

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?

È stato utile?

Soluzione

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top