JS的一道this例题解析

在学习js里this的指向时,发现了一道有点变态的面试题,看懂了对学习this应该是挺有帮助的

例题如下

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;

child1.show();
child2.show();
parent.show();

child1.change();
child1.show();

child2.change();
child2.show();

parent.show();

答案如下:

child1.show();//11 [1,2,1] 5
child2.show();//12 [1,2,1] 5
parent.show();//1 [1,2,1] 5

child1.change();
child1.show();//5 [1,2,1,11] 4

child2.change();
child2.show();//6 [1,2,1,11,12] 5

parent.show();//1 [1,2,1] 5

以下是我的理解
第一块没有使用change时,比较好理解,child继承了parent,所以可以使用show方法。首先输出show里面的this.a,由于此时调用者还是child,所以在child找到a=11。随后是show里的this.b,先查找child里面没有,就查找原型对象parent对象,然后输出里面的b,在b里面的this.a时,由于调用者现在是parent,所以this.a引用的也是parent里面的a。然后是this.c.demo,同样查到parent里面输出5。
第二块child1调用了change方法,这个地方的难点是this.b.push(this.a),push进去的依然是chid里面的a而不是parent里的a。因为这次的this.a所处的上下文是child,首先会在child里面查找,如果没有才会去原型里找。而前面this.a是已经在原型里面的环境,自然就只能查找原型了,如果原形parent里没有a,那就输出undefined。
第三块的难点在于,第二块的改动继续被沿用了,对child2实例也产生了改动。因为他们原型里指向的对象parent是同一个对象。parent在Child.prototype = new Parent()这个时候已经新建了实例对象并绑定在了child上面作为它的原型对象,child新建实例的时候并不会影响原型对象,因为就算child不创建实例,我们一样可以通过child.prototype操作赋进去的parent对象
第四块没有难点,前面改动的仅仅是它的一个实例,而parent本身没有受到影响

这个地方涉及的不仅仅是this的指向问题,还有一些继承或原型的知识,我的理解也不是很全面,可能在以后学的更透彻的时候会有不一样的想法

例题来源:
http://www.icafebolger.com/javascript/jsfunc.html

猜你喜欢

转载自blog.csdn.net/weixin_38958597/article/details/85325818