I was reading Introduction to Object-Oriented JavaScript from Mozilla Developer Network, time to learn so serious Javascript before start using node.js.
Anyway, inheritance thing seems so obscure to me. Copy and paste from the documentation:
// define the Person Class
function Person() {}
Person.prototype.walk = function(){
alert ('I am walking!');
};
Person.prototype.sayHello = function(){
alert ('hello');
};
This is easy, but things get complicated with Student
inheritance. Does anyone else think that the following three statements do essentially the same thing?
// define the Student class
function Student() {
// Call the parent constructor
Person.call(this);
}
// inherit Person
Student.prototype = new Person();
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
I understand the first one (calling the parent constructor) because is so similar to Java, PHP and so on. But then problems begin.
Why there is the need of calling Student.prototype
and ?Student.prototype.constructor
A clear explanation is needed. Why this code:
// define the Student class
function Student() {
// Call the parent constructor
Person.call(this);
}
var student1 = new Student();
is not enough for inheritance to work?
EDIT: regarding the constructor thing, it has been already answered here.