一道有意思的JavaScript 题目

今天在网上看到一道题,觉得很有意思就把它抄下来解了。题目是这样的:

 1            function Parent() {
 2                 this.a = 1;
 3                 this.b = [1, 2, this.a];
 4 
 5                 this.c = { demo: 5 };
 6                 this.show = function () {
 7                     console.log(this.a , this.b , this.c.demo );
 8                    /* alert(this.b);*/
 9                 }
10             }
11             function Child() {
12                 this.a = 2;
13                 this.change = function () {
14                     this.b.push(this.a);
15                     this.a = this.b.length;
16                     this.c.demo = this.a++;
17                      /* alert(this.b.length);*/
18                     /*alert(this.b);*/
19                 }
20             }
21             Child.prototype = new Parent();// 继承
22             var parent = new Parent();
23             var child1 = new Child();
24             var child2 = new Child();
25             child1.a = 11;
26             child2.a = 12;
27 
28             parent.show();//1 [ 1, 2, 1 ] 5 
29             child1.show();//11 [ 1, 2, 1 ] 5
30             child2.show();//12 [ 1, 2, 1 ] 5
31 
32             child1.change();
33             child2.change();
34 
35             parent.show();//1 [ 1, 2, 1 ] 5
36             child1.show();//5 [ 1, 2, 1, 11, 12 ] 5
37             child2.show();//6 [ 1, 2, 1, 11, 12 ] 5

下面让我们来跟着运行结果分析代码:

第一: parent.show();//1 [ 1, 2, 1 ] 5 :调用自己的方法,自己的属性,这个就比较简单了。 就不多说。

第二: child1.show();//11 [ 1, 2, 1 ] 5 :我们知道,Child 继承了parent ,而child1 是Child 的实例,所以此时看图:

因为 child1.a=11;所以child1.show 的时候 使用的是自己的 a这个值,与此同时,child1中没有b,所以根据原型链搜查值原理,这个会顺着原型链往上找,直到找到 Parent 中,而此时使用的就是Parent 的值,而因为this 是看谁在使用它,就指向谁,而此时使用的是此时是 Parent中的b ,故可以理解成 Parent.b=[1,2,Parent.a];  而 this.c = { demo: 5 },因为child 1也没有 c ,所以会找到 Parent 中的c ,故此时就是 11 [1,2,1] 5

child2 情况如同child 1.

 

child1.change();
child2.change(); //经历了这两个函数, this.b.push(this.a); this.b这个数组中压入值,第一次压入11,第二次压入12.    this.a = this.b.length; 将数组的长度赋值给a,第一次压入后长度是4 ,第二次是5 故this.c.demo = this.a++; 中 this.c=5,这里考察了a++赋值,先赋值后++ 。
此时数组变成[1,2,1,11,12]

这里提一下:
child1.change()时 this.c=4,而this.a++在赋值之后自增变成5.
child2.change()时 this.c=5;而this.a++自增变成6.
(我特地写这这两段是因为我在考虑自增的时候很郁闷,因为当child2.chang()已经执行完后,this.a++自增变成6 ,那么child1.show 和child2.show 为什么输出不同的this.a呢? 这个问题就考虑到了深复制的问题,child1与child2对child是深复制,他们之间的私有变量不会互相影响,而他们对parent是浅赋值,所以会共享this.c.demo
的值。

 *值得注意的是,当执行child1.chang() 和child2.chang()之后,他们两个都给自己添加了变量c.demo ,但是实际上并不会影响到parent 自身的c.demo的值,parent.show中调用的依旧是自己的c.demo,您可以修改parent中 demo的值就可以明显看出来了。

 

原文地址:https://www.cnblogs.com/wxhhts/p/9499265.html