For Example:
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.");
}
}
I know I can achieve this using:
function Student() {
this.studentId = 0;
}
Student.prototype = new Person();
Student.prototype.constructor = Person;
Student.prototype.sayHello = function () {
console.log("Hello, I am a student.");
}
But I'd like to continue to use style from the first example and have all my class methods defined in a single ".prototype" block if possible.
Take a look at the following answer on StackOverflow: https://stackoverflow.com/a/17893663/783743
This answer introduces the concept of prototype-class isomorphism. To put it simply a prototype object can be used to model a class. The following code is taken from the above answer:
Using the above method we can implement
Person
as follows:Inheritance however requires some additional work. So let's modify the
CLASS
function a little:We also need to define the
descriptorOf
function forCLASS
to work:Now we can create
Student
as follows:See the demo for yourself: http://jsfiddle.net/CaDu2/
If you need any help understanding the code then feel free to contact me.