例如:
function Person() {
//person properties
this.name = "my name";
}
Person.prototype = {
//person methods
sayHello: function() {
console.log("Hello, I am a person.");
}
sayGoodbye: function() {
console.log("Goodbye");
}
}
function Student() {
//student specific properties
this.studentId = 0;
}
Student.prototype = {
//I need Student to inherit from Person
//i.e. the equivalent of
//Student.prototype = new Person();
//Student.prototype.constructor = Person;
//student specific methods
//override sayHello
sayHello: function() {
console.log("Hello, I am a student.");
}
}
我知道我可以使用:
function Student() {
this.studentId = 0;
}
Student.prototype = new Person();
Student.prototype.constructor = Person;
Student.prototype.sayHello = function () {
console.log("Hello, I am a student.");
}
但我想继续使用第一个示例中的样式,并尽可能将我的所有类方法定义在一个“.prototype”块中。