每个实例都有一个到创建它的构造函数原型的链接。所以每个实例都共享原型成员。如果通过一个实例对共享原型成员进行更改,则会反映到所有其他实例。为什么这似乎不符合基本类型工作,因为可以看到下面:原型中原始类型的行为
//creating an empty object type
function OBJTYPE(){};
//adding primitive value and reference value as a memeber to
//the prototype of the object type
OBJTYPE.prototype.value = 0;
OBJTYPE.prototype.arr = ["red","green","blue"];
//creating instances of the object type
var obj1 = new OBJTYPE();
var obj2 = new OBJTYPE();
//outputting the prototype members through both the instances
document.write(obj1.value + "<br />"); //0
document.write(obj2.value + "<br />"); //0
document.write(obj1.arr + "<br />"); //red,green,blue
document.write(obj2.arr + "<br />"); //red,green,blue
//changing value of primitive member
obj1.value = 1; //creates a new instance property
//modifying the reference type member - pushing a value on the array
obj1.arr.push("black"); //modifies the prototype property
//outputting the prototype members through both the instances
document.write(obj1.value + "<br />"); //1 //.value from instance
document.write(obj1.__proto__.value + "<br />"); //0 //.value from prototype
//works in Firefox, Safari, and Chrome
document.write(obj2.value + "<br />"); //0 //.value from prototype
document.write(obj1.arr + "<br />"); //red,green,blue,black
document.write(obj2.arr + "<br />"); //red,green,blue,black
正如你可以在上面看到改变原始成员的价值创造,而不是覆盖同名属性调用value
上obj1
一个新的实例属性,在原型中。因此,当访问obj1.value
属性时,它会返回屏蔽原型属性的实例属性。这就是为什么两个实例显示不同值value
。
但是,这不引用类型的行为不像从上面可以看出。为什么?
很大,但有什么办法可以修改基本类型创建这样没有实例属性,但原型属性被修改 – Mahesha999
没有因为原始值没有任何修改。更准确地说,它们是不可改变的。 – Esailija
多亏了这一点,现在只是脱离主题,我试图用@提及你,但是当我提交评论时,它删除了提及。此外,当我点击@时,它并未向我显示列表中所有成员的列表弹出窗口,这是用于早期发生的。为什么? – Mahesha999