Когда вы используете super.fieldName
для доступа к полю родительского класса, вы фактически запрашиваете имя поля у prototype
родительского класса.
Таким образом, вы можете поверить, что вызов super(name);
из конструктора Son
устанавливает name
в прототипе родительского класса, но это не , поэтому он фактически устанавливает name
свойство унаследовано классом Son
, доступ к которому можно получить с помощью this.name
.
Поэтому я изменил ваш пример кода и показал, как на самом деле получить значение, вызвав super.fieldName
.В примере я добавил свойство age
в прототип класса Dad
и установил его значение на 50
, теперь в Son
классе printvariable()
будет правильно вызывать super.age
, ссылаясь на прототипкласс Dad
.
Вы можете увидеть его в действии, если будете использовать babel для его переноса на ES2015, после того как все классы в JavaScript на самом деле являются синтаксическим сахаром.
class Dad {
constructor(name) {
this.name = name;
Dad.prototype.age = 50; //adding property to prototype
}
printname() {
console.log(this.name);
var a = 2;
return a;
}
sendVal() {
console.log(this.name);
var a = 2;
return this.name;
}
}
class Son extends Dad {
constructor(name) {
super(name);
}
printname() {
console.log(super.printname());
}
printvariable() {
console.log(`super.name will be undefined, as not present in prototype of the Dad class: ${super.name}`);
console.log(`super.age will have a value of 50, present in the prototype of the Dad class: ${super.age}`);
console.log(`this.name will be jack, as it is set from the constructor of the Son class: ${this.name}`);
}
getvalue() {
console.log(super.sendVal());
}
}
var o1 = new Dad('jackson');
var o2 = new Son('jack')
o1.printname();
o2.printname();
o2.printvariable();
o2.getvalue();