JS:原型链的笔试题
原题:
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(); var parent = new Parent(); var child1 = new Child(); var child2 = new Child(); child1.a = 11; child2.a = 12; parent.show(); //1 [1, 2, 1] 5 child1.show(); //11 [1, 2, 1] 5 child2.show(); //12 [1, 2, 1] 5 child1.change(); child2.change(); 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
打印结果:
1 [1, 2, 1] 5
11 [1, 2, 1] 5
12 [1, 2, 1] 5
1 [1, 2, 1] 5
5 [1, 2, 1, 11, 12] 5
6 [1, 2, 1, 11, 12] 5
理解:
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() 假设O1{a=2,change(),O2-->Parent(){a=1,b=[1,2,1],c:{demo=5},show(){},O3-->Parent.prototype} var parent = new Parent(); // parent() O4{a=1,b[1,2,1],c{demo:5},show(){},O3} var child1 = new Child(); // child1(){a=11,,change(){},Parent(){a=1,b=[1,2,1],c:{demo=5},show(){},O3} var child2 = new Child(); // child2(){a=12,,change(){},Parent(){a=1,b=[1,2,1],c:{demo=5},show(){},O3} child1.a = 11; child2.a = 12; parent.show(); //打印 1,[1,2,1],5 child1.show(); //打印 5,[1,2,1,11],5 /* 先运行Child, a = 11, b在Parent中去引用[1,2,1]添加11成员[1,2,1,11] a=b.length==>4 , c.demo=4 , 这是Child函数没有的属性, 则创建一个c.demo ,a先取值再++ a = 5 覆盖a=11 此时 child1(){a=5,,change(){},O2{O3}} child1中没有show函数 就到原型对象中去找 这时的原型对象是Parent,调用Parent中的show函数 */ child2.show(); /* 打印 6,[1,2,1,11,12],5 取a=12 ,在原型对象Parent中引用b,[1,2,1,11]添加成员12 ,得到[1,2,1,11,12],a = b.length ==>5,c.demo = 5 同上 a = 6 child1(){a=6,,change(){},Parent(){a=1,b=[1,2,1,11,12],c:{demo=5},show(){},O3} show函数中不能调用Child的c.demo成员 因此输出的是show中的c.demo = 5 */ child1.change(); //child1(){a=6,,change(){b},Parent(){a=1,b=[1,2,1,11,12],c:{demo=5},show(){},O3}