Reputation: 87
class Base{
constructor(val){
this.val = val;
}
basep = 'default1';
basef(){
return 2;
}
}
class Test1 extends Base{
constructor(val,name){
super(val);
this.name=name;
}
getp(){
console.log(this.name,this.val);
console.log(this.basep); //(in case of proerty) result: 'default1'. if "this" is changed to "super" ===> result: undefined
console.log(super.basef()); //(in case of methods) this and super both work.
}
}
test= new Test1(1,3);
test.getp();
In java 'this' and 'super' worked both fine to get parents property but it seems in javascript only this works. why is the difference?
Upvotes: 1
Views: 565
Reputation: 664385
In Java, attribute names are put in a scope, and you can have two different attributes with the same name if they were created by different classes. This is not how it works in JavaScript with prototypical inheritance at all, though.
In JavaScript, data properties (that are created by assignment) are owned by the object itself. The parent constructor created the .basep
property directly on the child instance. this.hasOwnProperty('basep')
will be true
.
The super
keyword is used to access properties on the parent's .prototype
object, regardless of what the current this
value is, but still allows calling them on the this
object. The basef
method lives as a property on Base.prototype
, basep
does not.
Upvotes: 2