// 实现原型链的基本模式
function Super() {
this.value = 'Super';
this.color = ["red", "blue", "green"];
}
Super.prototype.getSuperValue = function () {
return this.value;
}
function Sub() {
this.a = 'a'
this.subValue = 'Sub';
}
Sub.prototype = new Super();
Sub.prototype.getSubValue = function () {
return this.subValue;
}
var subObj1 = new Sub();
subObj1.subValue = 'subObj1'
console.log(subObj1.getSubValue());//subObj1
console.log(subObj1.getSuperValue());//Super
console.log(subObj1.a);//a
subObj1.a = 'subObj1a';
console.log(subObj1.a);//subObj1a
subObj1.color.push('pink');
console.log(Sub.prototype.color);//[ 'red', 'blue', 'green', 'pink' ]
console.log(subObj1.color);//[ 'red', 'blue', 'green', 'pink' ]
subObj1.color = ['a', 'b'];
console.log(Sub.prototype.color);//[ 'red', 'blue', 'green', 'pink' ]
console.log(subObj1.color);//['a', 'b']
subObj1.color.push('c');//子类自己有了color,就不会去找原型的color了,所以这时候更改的是实例自己的color
console.log(Sub.prototype.color);//[ 'red', 'blue', 'green', 'pink' ]
console.log(subObj1.color);//[ 'a', 'b', 'c' ]
var subObj2 = new Sub();
console.log(subObj2.getSubValue());//Sub
console.log(subObj2.getSuperValue());//Super
console.log(subObj2.a);//a
Sub.prototype.value = 'hello world';
console.log(subObj1.getSuperValue());//hello world
console.log(subObj2.getSuperValue());//hello world
console.log(Sub.prototype.color);//[ 'red', 'blue', 'green', 'pink' ]
console.log(subObj2.color);//[ 'red', 'blue', 'green', 'pink' ]
1.每个实例单独保存构造函数的变量,互不影响
2.同类型的实例共同拥有原型拥有的变量,只要原型的指向不变,修改其中的某一变量
所有实例的该变量值都会对应修改,即互相影响
3.读取某一实例的变量,先读实例有没有,没有才会去原型链上找
4.所有函数的默认原型都是Object的实例
5.如果原型中包含引用类型值,则通过实例可以更改这个引用值,而不是常规的->构造函数名.prototype.引用类型变量