0
我从下面的例子中学习了OOP Js。这一切都很好,很酷,我只是想知道是否有可能访问学生的原型方法sayGoodBye,我理解这可能是实现在PHP中使用抽象方法,但只是想知道有没有办法在JS做到这一点OOP。由于父访问子原型函数
我可能都不是很清楚,代码示例完美只是想知道,如果能做到
Person.prototype.walk = function(){
//Goog bye is the method in Student.
this.sayGoodBye();
};
工作代码。
function Person(firstName) {
this.firstName = firstName;
}
Person.prototype.walk = function(){
alert("I am walking!");
};
Person.prototype.sayHello = function(){
alert("Hello, I'm " + this.firstName);
};
function Student(firstName, subject) {
Person.call(this, firstName);
this.subject = subject;
};
Student.prototype = Object.create(Person.prototype); // See note below
Student.prototype.constructor = Student;
Student.prototype.sayHello = function(){
alert("Hello, I'm " + this.firstName + ". I'm studying " + this.subject + ".");
};
Student.prototype.sayGoodBye = function(){
alert("Goodbye!");
};
var student1 = new Student("Janet", "Applied Physics");
student1.sayHello(); // "Hello, I'm Janet. I'm studying Applied Physics."
student1.walk(); // "I am walking!"
student1.sayGoodBye(); // "Goodbye!"
alert(student1 instanceof Person); // true
alert(student1 instanceof Student); // true
你不是已经成功访问(并调用)代码中的'sayGoodBye'方法吗?我真的不明白你的问题是什么,代码看起来很完美。 *您需要访问该方法的位置? – Bergi
@bergi我有更新的问题,我的意思是访问父功能内的子功能,如果我想打电话给再见()内步行() – Bruce
当然,你可以在那里调用它(它会在所有'学生'实例,而不是在'父')。但是,您遇到拼写错误,该方法被命名为'.sayGoodBye()'而不是'.goodbye()'。 – Bergi