Reputation: 597
I'm new to JS and have a question about inheritance. How are inherited properties accessed through the child class?
Lets say I have the following classes:
function ParentClass(parentArg) {
this.parentProperty = parentArg;
}
function ChildClass(childArg1, childArg2) {
this.prototype = new ParentClass(childArg1);
this.childProperty = childArg2;
}
And at some point an object is created of ChildClass, like so:
var foo = new ChildClass('value 1', 'value 2');
Then how can a parent property be accessed from the instance of the child? The following returns 'undefined'.
var parentValue = foo.parentProperty;
Much appreciated. Cheers
Upvotes: 3
Views: 3753
Reputation: 3238
For ES6, you use extends, eg
class A { prop = "prop" }
class B extends A{}
new B();
Upvotes: -1
Reputation: 13106
The problem is because you can't assign to a prototype property before the object definition is declared:
Doesn't work:
function Parent() {
this.parentProperty = "test";
}
function Child() {
// This doesn't work because the prototype is set inside of the definition
this.prototype = new Parent();
}
var child = new Child();
alert(child.parentProperty);
Works
function Parent() {
this.parentProperty = "test";
}
function Child() {
// Define prototype outside of function constructor
}
Child.prototype = new Parent();
var child = new Child();
alert(child.parentProperty);
Also notice that in the second example we assign to Child.prototype and not new Child().prototype
Upvotes: 0
Reputation: 239443
If you want to initialize the parentProperty
, you have to do it like this
function ParentClass(parentArg) {
this.parentProperty = parentArg;
}
function ChildClass(childArg1, childArg2) {
ParentClass.call(this, childArg1);
this.childProperty = childArg2;
}
And to actually inherit Parent't methods, you might want to do
ChildClass.prototype = Object.create(ParentClass.prototype);
After making these changes,
var foo = new ChildClass('value 1', 'value 2');
console.log(foo);
# { parentProperty: 'value 1', childProperty: 'value 2' }
Upvotes: 3