鍍金池/ 問答/HTML5  HTML/ 為什么打印的結(jié)果this.a不是10

為什么打印的結(jié)果this.a不是10

       function f1() {
            this.a = 1;
            this.b = [1, 2, this.a];
            this.show = function(){
                console.log(this.b)
            }
        }

        function f2() {
            this.a = 2;
        }

        f2.prototype = new f1();

        var a2 = new f2();
        a2.a = 10;
        console.log(a2.show()); //[1,2,1]?
回答
編輯回答
孤島

具體原因如@cc_christian所說。

說句題外話。

a2.a 這個(gè)屬性是a2的本地屬性,你對它的賦值不會(huì)去改變a2.__proto__.a的屬性。

等于是給a2新增了一個(gè)屬性。

圖片描述

2017年5月5日 02:37
編輯回答
傻叼

數(shù)組存的不是變量

var a = [], b = 1;
a[0] = b;
console.log(a);//[1]
b = 2;
console.log(a); //[1]

2017年1月27日 09:54
編輯回答
喵小咪
function f1() {
  this.a = 1;
  console.log(this);
  this.b = [1, 2, this.a];
  this.show = function() {
    console.log(this);
    console.log(this.b);
  };
}

function f2() {
  this.a = 2;
}

f2.prototype = new f1();
這句話就相當(dāng)于:

f2.prototype = {
  a: 1,
  b: [1, 2, this.a],
  show: function() {
    console.log(this.b);
  }
};

var a2 = new f2();
再來看這句話相當(dāng)于:

a2 = {
  a: 2
};

a2.a = 10;
這句話就相當(dāng)于把上面的a給覆蓋了:

a2 = {
  a: 10
};

其中又有這樣的關(guān)系:
a2.__proto__ == f2.prototype; 這個(gè)不需要解釋吧,因?yàn)閍2是f2的實(shí)例,教科書就是這么寫的

f2.prototype = new f1(); 已知條件

所以我們可以得出:

a2.__proto__ = {
  a: 1,
  b: [1, 2, this.a],
  show: function() {
    console.log(this.b);
  }
};

到這一步已經(jīng)很清晰明了了, 我們再來看看最關(guān)鍵的一部分

console.log(a2.show());

從上面可以得知的條件:

a2 = {
  a: 10
};

a2.__proto__ = {
  a: 1,
  b: [1, 2, this.a],
  show: function() {
    console.log(this.b);
  }
};

好了,發(fā)現(xiàn) a2 沒有 show 屬性,那怎么辦,沿著原型鏈也就是 __proto__ 找,最后執(zhí)行其實(shí)就是 a2.__proto__.show(),不信自己去瀏覽器執(zhí)行以下,看是不是和 a2.show() 的結(jié)果是否一致。

a2.__proto__.show() = function() {
  console.log(this.b);
}

最后就成了這樣,接下來我們要研究的就是這個(gè)函數(shù)執(zhí)行的 this 是啥,知道this規(guī)律應(yīng)該不難看出來,這里的 this 就是a2.__proto__ ,那么最后就成了 a2.__proto__.b=[1,2,this.a],那么這個(gè) this 指向誰呢?我就不多說了.

其實(shí)

a2.__proto__ = {
  a: 1,
  b: [1, 2, this.a],
  show: function() {
    console.log(this.b);
  }
};

還可以這么簡化,去掉 this,跟這個(gè)是等價(jià)的

a2.__proto__ = {
  a: 1,
  b: [1, 2, 1],
  show: function() {
    console.log(this.b);
  }
};

不信把這段代碼控制臺(tái)輸入一下,最后運(yùn)行的結(jié)果就是這個(gè),千真萬確。

所以最后結(jié)果是 [1,2,1]

2017年3月2日 15:27