function Parent() {
this.a = 1;
this.b = [1, 2, this.a];
this.c = {
demo: 5
};
this.show = function() {
console.log(this.a, this.b, this.c.demo);
}
}
function Child() {
this.a = 2;
this.change = function() {
this.b.push(this.a);
this.a = this.b.length;
this.c.demo = this.a++;
}
}
Child.prototype = new Parent(); //改变Child函数的原型对象=Parent()函数运行后所创建的对象 后面的代码用Child函数创建的对象的原型对象都是 Child.prototype =={a = 1,b = [1, 2, 1],c = {demo: 5},show = function() {console.log(this.a, this.b, this.c.demo);}}
var parent = new Parent(); //创建一个由Parent函数运行后的对象 parent={a = 1,b = [1, 2, 1],c = {demo: 5},show = function() {console.log(this.a, this.b, this.c.demo);}}
var child1 = new Child(); //child1={a = 2,change = function() {this.b.push(this.a);this.a = this.b.length;this.c.demo = this.a++;}
var child2 = new Child(); //child2={a = 2,change = function() {this.b.push(this.a);this.a = this.b.length;this.c.demo = this.a++;}
child1.a = 11; //child1的原型链上是否有a成员 都会把a添加/更新到child1自己上 child1={a = 11,change = function() {this.b.push(this.a);this.a = this.b.length;this.c.demo = this.a++;}
child2.a = 12; //同上 child2={a = 12,change = function() {this.b.push(this.a);this.a = this.b.length;this.c.demo = this.a++;}
parent.show(); //调用parent对象的show()方法 console.log(this.a, this.b, this.c.demo) 打印parent对象的a,b,c.demo属性 结果 1,[1, 2, 1],5
child1.show(); //调用child1对象的show()方法 因为child1没有show方法 所以找到child1函数的原型对象Child.prototype 因此执行console.log(this.a, this.b, this.c.demo)代码,
//这里的this就是child1,然后因为child1没有b,c属性,所以取它的原型对象Child.prototype中的b,c值。因此打印 11,[1,2,1],5
child2.show(); //调用child2对象的show()方法,原理跟上面child1.show()一样 ,因此打印 12,[1,2,1],5
child1.change(); //调用child1对象的change()方法,执行这个函数function() {this.b.push(this.a);this.a = this.b.length;this.c.demo = this.a++;} 这里面的this都是child1
//从代码 this.b.push(this.a);分析 这里因为在child1对象中没找到b属性就去原型对象找有个b属性向里面添加了child1的a属性;注意:b是原型对象的属性 但是这个代码没有修改b 只是操作了b内部的数据是可以让原型对象内部的数据改变
//从代码 this.a = this.b.length 分析 child1对象的a属性值变为原型对象Child.prototype中的b数组的长度 a=4
//从代码 this.c.demo = this.a++;分析 改变原型对象Child.prototype中的 c.demo=4 运行后a自增1 a=5
//执行完后 Child.prototype={a = 1,b = [1, 2, 1,11],c = {demo: 4},show = function() {console.log(this.a, this.b, this.c.demo);}}
//child1={a = 5,change = function() {this.b.push(this.a);this.a = this.b.length;this.c.demo = this.a++;}
child2.change(); //调用child2对象的change()方法,原理跟child1一致
//执行完后 Child.prototype={a = 1,b = [1, 2, 1,11,12],c = {demo: 5},show = function() {console.log(this.a, this.b, this.c.demo);}}
//child2={a = 6,change = function() {this.b.push(this.a);this.a = this.b.length;this.c.demo = this.a++;}
parent.show(); //打印 1,[1,2,1],5
child1.show(); //打印 5,[1,2,1,11,12],5
child2.show(); //打印 6,[1,2,1,11,12],5