Overriding class fields

Can Avcı
1 min readJan 2, 2023

we can not only override methods but also fields . However there is tricky behavior when we access to the overridden field in the parent constructor and it is quite different from the most of the programming languages.

class Animal {
name = 'animal';

constructor() {
alert(this.name); // (*)
}
}

class Rabbit extends Animal {
name = 'rabbit';
}

new Animal(); // animal
new Rabbit(); // animal

what is interesting , in both cases new Animal() and new Rabbit(), the alert in the line (*) shows animal.
in other words a parent constructor always uses its own value
If it’s not clear yet, please compare with methods.

class Animal {
showName() { // instead of this.name = 'animal'
alert('animal');
}

constructor() {
this.showName(); // instead of alert(this.name);
}
}

class Rabbit extends Animal {
showName() {
alert('rabbit');
}
}

new Animal(); // animal
new Rabbit(); // rabbit

now the output is different . that is what we naturally expect when the parent constructor is called in the derived class.
But for fields it is not so.

the reason is the initialization order since super class constructor is called before the derived ones.

--

--