I'm confused about javascript inheritance.
Consider the following code:
function parent(firstname, lastname) {
this.firstname = firstname || "abc";
this.lastname = lastname || "def";
}
function child() {
this.childname = "xys";
}
parent.prototype.Greetings = function () {
alert("sayhi");
}
child.prototype = Object.create(parent.prototype);
var child1 = new child();
Now, does the child1 object have access to the firstname and lastname properties?
I can access the Greetings method (because it's in the prototype).
If I try to access these, it is showing as undefined.
What changes have to be made to access these variables?
You have to call the parent constructor in the child constructor:
JavaScript "inheritance" is a lot less magical (i.e. implicit) than in other languages (before ES6 classes at least).
In your example you have a function
parentwhich sets two properties onthis. However, nowhere in your code are you callingparent, so these properties will never be set.In order to set them we need to apply
parentto the newchildinstance, which is done by callingparent.call(this);.Since
parentaccepts arguments, you probably want to pass them throughchildeventually:Related: Benefits of using `Object.create` for inheritance