【发布时间】:2012-02-23 08:49:44
【问题描述】:
我正在试验 JavaScript 继承。基本上,我正在关注this 教程。
我看到,使用那里的代码,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:对不起,如果我的问题的语气有问题。我从没想过粗鲁。
-
@hrishikeshp19:不,我认为你没有。 :-)
标签: javascript inheritance prototype