2022-04-18

Why do extended classes uses prototypes for methods but not for fields?

Looking at this simple code :

class Animal {
    someField = 42;
    animalFunc() {
        console.log('animal')
    }
}
class Lion extends Animal {
    lionFunc() {
        console.loge('lion')
    }
}
let lion = new Lion();
console.log(lion)

Result in Chrome is :

enter image description here

As we can see, the instance methods are on the prototype (for each constructor function)

Question:

Why are fields, as opposed to methods, not on the prototype?
I mean , someField is in Animal not in Lion.



No comments:

Post a Comment