例如,你有代码:
function Animal() {
}
Animal.prototype.name="animal";
function Dog() {
}
Dog.prototype = new Animal
Dog.prototype.constructor=Dog;
Dog.prototype.name="dog";
object1 = new Animal();
object2 = new Dog();
因此,您有两个对象实例,看起来像(例如,您可以在 Chrome devtools 或 FF firebug 或...中进行检查):
object1:
__proto__: (is ref into an Animal.prototype object)
constructor: function Animal()
name: "animal"
__proto__: Object (is ref into an Object.prototype object)
object2:
__proto__: (is ref into an Dog.prototype object)
constructor: function Dog()
name: "dog"
__proto__: (is ref into an Animal.prototype object)
constructor: function Animal()
name: "animal"
__proto__: (is ref into an Object.prototype object)
当你运行下一个代码时(例如):
alert(object1.name); // displayed "animal"
alert(object2.name); // displayed "dog"
发生了什么? 1) Javascript 在对象实例中查找属性名称(在object1 或object2 中)。 2) 找不到时,在对象实例的proto属性中查找(与类函数的原型相同)。 3)当没有找到时,它在 proto 的 proto 和 next 和 next 中查找,而未找到 name 属性和其他 proto 找到。如果作为搜索属性的结果找到,则返回值,如果没有找到,则返回undefined。
如果你执行下一个代码会发生什么:
object2.name = "doggy";
结果你有object2:
object2:
name: "doggy"
__proto__: (is ref into an Dog.prototype object)
constructor: function Dog()
name: "dog"
__proto__: (is ref into an Animal.prototype object)
constructor: function Animal()
name: "animal"
__proto__: (is ref into an Object.prototype object)
属性直接赋值给实例对象,但原型对象保持不变。当你执行时:
alert(object1.name); // displayed "animal"
alert(object2.name); // displayed "doggy"
当您需要创建|更改类的 shared 属性时,可以使用以下算法中的一个:
1)
Animal.prototype.secondName="aaa";
alert(object1.secondName); // displayed "aaa"
alert(object2.secondName); // displayed "aaa"
Animal.prototype.secondName="bbb";
alert(object1.secondName); // displayed "bbb"
alert(object2.secondName); // displayed "bbb"
// but
Animal.prototype.secondName="ccc";
object1.secondName="ddd";
alert(object1.secondName); // displayed "ccc"
alert(object2.secondName); // displayed "ddd"
2)
在函数类原型中创建object类型的属性,并为该对象的属性赋值。
Animal.prototype.propObject={thirdName:"zzz"};
alert(object1.propObject.thirdName); // displayed "zzz"
alert(object2.propObject.thirdName); // displayed "zzz"
Animal.prototype.propObject.thirdName="yyy";
alert(object1.propObject.thirdName); // displayed "yyy"
alert(object2.propObject.thirdName); // displayed "yyy"
object1.propObject.thirdName="xxx";
alert(object1.propObject.thirdName); // displayed "xxx"
alert(object2.propObject.thirdName); // displayed "xxx"
object2.propObject.thirdName="www";
alert(object1.propObject.thirdName); // displayed "www"
alert(object2.propObject.thirdName); // displayed "www"