我正在嘗試JavaScript的繼承。基本上,我正在遵循this教程。爲什麼我們需要在JavaScript中調用父構造函數繼承
我看到,在那裏的代碼中,Person類被實例化了兩次。請看this fiddle。
我所做的是註釋掉:
Person.call(this)
而且繼承工作得很好。
在原始代碼中,行
Person.call(this)
被使用。是否需要使用子範圍調用父構造函數?
請你也給一些解釋,我是OO JavaScript的新手。
非常感謝。
編輯:
我在小提琴代碼如下:
function Person(gender) {
this.gender = gender;
document.write('Person instantiated</br>');
}
Person.prototype.walk = function(){
document.write("is walking</br>");
};
Person.prototype.sayHello = function(){
document.write("Hello</br>");
};
Person.prototype.sayGender = function(){
document.write(this.gender + "</br>");
};
function Student() {
//Person.call(this);
document.write('Student instantiated</br>');
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
Student.prototype.sayHello = function(){
document.write("Student says Hello</br>");
}
Student.prototype.sayGoodBye = function(){
document.write("Student says goodbye</br>");
}
var student1 = new Student();
student1.sayHello();
student1.walk();
student1.sayGoodBye();
document.write(student1 instanceof Person);
document.write("</br>");
document.write(student1 instanceof Student);
@ T.J.Crowder:很抱歉,如果我的問題的基調已經出了問題。我從來沒有打算過無禮。 – riship89 2012-02-23 09:00:47
'@ hrishikeshp19':不,我認爲你沒有。 :-) – 2012-02-23 09:25:40