昨天遇到的一個問題:對于兩個普通的對象a,bvar a = { foo:1, methodA:function(){ console.log(this.foo);
}
}var b = { bar:2, methodB: function(){ console.log(this.bar);
}
}可以不考慮執行環境的兼容性,實現下面要求:1 執行a.methodA()輸出1;2.執行a.methodB()輸出2;3.執行b.bar=3;a.methodB()輸出3上面的就是題目,首先想到的就是繼承,a繼承b,可以直接調用b的methodB方法。在題目的基礎上,我會這么實現的:function A(){ this.foo = foo; this.methodA = function(){ console.log(this.foo);
}
B.call(this) //實現繼承
}function B(){ this.bar = bar; this.methodB = function(){ console.log(this.bar);
}
} var a = new A(); var b = new B();執行下面的代碼:a.methodA() //輸出1;a.methodB() //輸出2;b.bar=3;a.methodB() //仍輸出2很顯然不符合要求。求大神告知產生的原因和解決的方法。 難道是我一開始就理解的不正確嗎?
關于Js繼承的一個小問題
子衿沉夜
2018-09-20 10:15:13