每个实例都有一个指向创建它的构造函数原型的链接。所以每个实例都共享原型成员。如果通过一个实例对共享原型成员进行更改,它会反映到所有其他实例。为什么这似乎不适用于原始类型,如下所示:
//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
on的新实例属性obj1
,而不是覆盖原型中相同的命名属性。因此,当访问obj1.value
属性时,它会返回掩盖原型属性的实例属性。这就是为什么两个实例实例显示不同的value
.
但是,从上面可以看出,这不引用类型的行为并不相似。为什么?