Reputation: 4818
I am moving my head around JavaScript prototypical Inheritance. I am taking the help of following link: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance
I have a person object:
function Person(first, last, age, gender, interests) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
};
I have inherited it to teacher object:
function Teacher(first, last, age, gender, interests, subject) {
Person.call(this, first, last, age, gender, interests);
this.subject = subject;
}
Now, I defined a function on Person prototype:
Person.prototype.sayHello = function (){
console.log("hello");
}
Now, I want to call it via teacher:
var teacher = new Teacher("khan","khan",1,"mile","hockey","english");
teacher.prototype.sayHello();
It gives:
Uncaught TypeError: Cannot read property 'sayHello' of undefined at :1:19
Calling it directly yields the same result:
teacher.sayHello();
Let me make constructor right:
Teacher.prototype = Object.create(Person.prototype);
teacher.sayHello();
VM203:1 Uncaught TypeError: teacher.sayHello is not a function at :1:9
Same result. What am I missing?
Upvotes: 0
Views: 34
Reputation: 68655
You are just calling the Person
function and pass to him the context which uses that to initialize the properties. You call it like if you call another function inside it. Person
is not in the prototype chain of the Teacher
. You also need to explicitly add it into the chain.
function Person(first, last, age, gender, interests) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
};
function Teacher(first, last, age, gender, interests, subject) {
Person.call(this, first, last, age, gender, interests);
this.subject = subject;
}
// Set the prototype an empty object which prototype is the Person.prototype
Teacher.prototype = Object.create(Person.prototype);
// Preserve the constructor
Teacher.constructor = Teacher;
Person.prototype.sayHello = function (){
console.log("hello");
}
var teacher = new Teacher("khan","khan",1,"mile","hockey","english");
teacher.sayHello();
Upvotes: 2