I am experimenting with JavaScript Inheritance. Basically, I am following this tutorial.
I see that, with the code there, the Person class is instantiated twice. Please have a look at this fiddle.
What I did is comment out:
Person.call(this)
And the inheritance is working just fine.
In the original code, the line
Person.call(this)
is used. Is there a need of calling parent constructor with child scope?
Could you please also give some explanation, I am new to OO JavaScript.
Thanks a lot.
EDIT:
My code in the fiddle is as follows:
function Person(gender) {
this.gender = gender;
document.write('Person instantiated</br>');
}
Person.prototype.walk = function(){
document.write("is walking</br>");
};
Person.prototype.sayHello = function(){
document.write("Hello</br>");
};
Person.prototype.sayGender = function(){
document.write(this.gender + "</br>");
};
function Student() {
//Person.call(this);
document.write('Student instantiated</br>');
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
Student.prototype.sayHello = function(){
document.write("Student says Hello</br>");
}
Student.prototype.sayGoodBye = function(){
document.write("Student says goodbye</br>");
}
var student1 = new Student();
student1.sayHello();
student1.walk();
student1.sayGoodBye();
document.write(student1 instanceof Person);
document.write("</br>");
document.write(student1 instanceof Student);
@hrishikeshp19: No, I didn't think you did. :-)