我从以下示例中学习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
答案 0 :(得分:1)
与PHP不同,JavaScript在语言本身中没有类似抽象方法的东西;如果要在扩展原型的对象中强制实现,可以编写如下内容:
Person.prototype.sayGoodbye = function() {
throw "You must implement me!";
};