我正在閱讀這本關於繼承的JS書,我對每一行都在做什麼感到困惑。如果我的理解是正確的,有人可以告訴我。JavaScript中的繼承
function classA(sColor){
this.color = sColor;
this.sayColor = function(){
alert(this.color);
};
}
function ClassB(sColor, sName){
this.newMethod = classA; //assigning a reference to a parent class
this.newMethod(sColor); //calling the constructor of the parent class
//question: so what is 'this' then? from my understanding when we call 'new ClassB('a','b')'
//we instantiate a new object and that new object becomes the 'this' in this case. Does this
//line mean we are converting the this to classA?
delete this.newMethod; //deleting reference to the CONSTRUCTOR of the parent class
this.name = sName;
this.sayName = function(){
alert(this.name);
}
}
如果這是你的書給你的繼承模式,我會去買另一本書。例如Crockford的Good Parts。 – Magnar 2011-06-11 19:06:29
我很少在js中使用繼承,但理解'this'很重要。如果你的目標是理解那很酷的事情,但是如果你想了解繼承,那麼它不會被使用。至少繼承是像你在上面那樣使用的。 – William 2011-06-11 19:07:17
這是本書所展示的第一個繼承例子,是的,我試圖瞭解代碼中每個地方的「this」是什麼。 – denniss 2011-06-11 19:09:57