標籤:img http 不同 深複製 私人變數 alt 運行 his 沒有
今天在網上看到一道題,覺得很有意思就把它抄下來解了。題目是這樣的:
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 ] 530 child2.show();//12 [ 1, 2, 1 ] 531 32 child1.change();33 child2.change();34 35 parent.show();//1 [ 1, 2, 1 ] 536 child1.show();//5 [ 1, 2, 1, 11, 12 ] 537 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的值就可以明顯看出來了。
一道有意思的JavaScript 題目