javascript原型链中 this 的指向

为了弄清楚Javascript原型链中的this指向问题,我写了个代码来测试:

var d = {
                d: 40
            };
            var a = {
                x: 10,
                calculate: function (z) {
                    return this.x + this.y + z + this.d
                },
                __proto__:d
            };

            var b = {
                y: 20,
                __proto__: a
            };

            var c = {
                y: 30,
                __proto__: a
            };

  运行如下的代码进行测试:

console.log(b.calculate(30)); // 100
console.log(c.calculate(40)); // 120

  从这个结果中可以看出 this.y 和 this.d 都获取到了值。但是如何找到值的呢。

翻阅资料得出:this这个值在一个继承机制中,仍然是指向它原本属于的对象,而不是从原型链上找到它时,它所属于的对象。

    此时我们得出 b.calculate(30)中的this指的就是 b 对象。

  1. this.x的值首先在 b对象中找,没找到,就沿着原型链找,在b的原型a中找到了值是10。

  2.this.y的值首先在 b对象中找,找到了,值为20.

   3.this.d的值首先在b对象中找,没找到,就沿着原型链找,在b的原型a中也没找到,然后在a的原型d中找,找到了值是40.

      4.此时运算 this.x + this.y + z + this.d=10+20+30+40=100.

  同理: c.calculate(40) 的值就是 10+30+40+40=120

 此时我们把代码再修改下:

var d = {
                d: 40
            };
            var a = {
                x: 10,
                calculate: function (z) {
                    console.log(x);
                    console.log(y);
                    console.log(z);
                    console.log(d);
                    return x + y + z + d //去掉了this
                },
                __proto__:d
            };

            var b = {
                y: 20,
                __proto__: a
            };

            var c = {
                y: 30,
                __proto__: a
            };

  在运行:

console.log(b.calculate(30))

  得出结果:

 此时在 方法calculate中是没有定义 x 这个变量的。 所以就 提示 x is not defined.

原文地址:https://www.cnblogs.com/huaan011/p/6812973.html