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
  •  | 
  •  

문제

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?

도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top