Let’s create Javascript class and object with this new class:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
getHeight() { return this.height }
state = 'some state'
}
const rect = new Rectangle(1, 2);
rect._proto_.state
undefined
rect._proto_.getHeight
ƒ getHeight() { return this.height }
rect.state
'some state'
As you see, methods are stored in prototype object, but fields are stored in instance of the object why is that?
If the field ‘state’ stored in prototype it would be available in all object instances of the same type and would store state for all rectangles. This is not what we expect when using class. So when we store field in object, it is more intuitive. Field – is state and it belongs to object, method is behaviour and it belongs to a class.
Leave a Reply