function SuperType(name) {
this.name = name;
this.color = ['red', 'green', 'yellow'];
}
SuperType.prototype.sayName = function () {
console.log(this.name);
};
function SubType(name, age) {
//借用构造函数继承属性
SuperType.call(this, name);
this.age = age;
}
//用原型来继承方法
SubType.prototype = new SuperType();
//SubType.prototype.constructor = SubType;
Object.defineProperty(SubType.prototype, 'constructor', {
value: SubType,
enumerable: false
});
SubType.prototype.sayAge = function () {
console.log(this.age);
};
var instance = new SubType("Sub1", 20);
console.log(instance);
instance.color.push("black");
console.log(instance.color);//["red", "green", "yellow", "black"]
delete instance.color;
console.log(instance.color);//删除之后color变成SuperType的实例的属性
instance.sayName();//Sub1
instance.sayAge();//20
instance.color.push("deeppink");//当前实例没有color属性.所以添加到了SuperType的color上
/*
*__proto__: SuperType
name: undefined
color: (4) ["red", "green", "yellow", "deeppink"]
*/
console.log(instance.color);// ["red", "green", "yellow", "deeppink"]
var instanceSup = new SuperType();//新创建一个SuperType的实例,检测引用类型color是否受实例影响 ,是否还有原型链实现继承的问题
console.log(instanceSup.color);//["red", "green", "yellow"] 不受影响
var instance2 = new SubType("Sub2", 20);
console.log(instance2.color);//["red", "green", "yellow"] 因为这个color是SubType的实例新创建的属性,将原来的color覆盖了所以不受影响
delete instance2.color;//将SubType的实例上的删除,再搜索就会找到SuperType上的color属性
console.log(instance2.color);//["red", "green", "yellow", "deeppink"] 已经受instance影响,instance改变了SuperType的color属性,原型对象上的属性是所有实例共享的
instance2.sayName();//Sub2
instance2.sayAge();//20