功能声明:
function F(){
this.x=1;
}
原型:
function F(){}
F.prototype.x=1;
函数声明中的原型:
function F(){ //UPDATE: will throw type error when instantiating. thank you @cookie monster
this.prototype.x=1;
}
有什么区别?什么时候使用各种方式更好?
答案 0 :(得分:1)
值将与所有实例共享,而构造函数中的一个值与每个实例无关。
错误的例子
function F(){}
F.prototype.x=1;
a = new F();
b = new F();
a.x = 2;
alert(b.x); //outputs 2 - EDIT: actually 1
编辑:这是正确的:
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
或者这个:
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