Reputation:
class Message {
constructor(text) {
this.text = text;
}
toString() {
return this.text;
}
}
class ErrorMessage extends Message {
constructor(text, code) {
super(text);
this.code = code;
}
}
const message = new ErrorMessage('Test', 404);
What exactly is prototype, let's say if we call: ErrorMessage.prototype or Message.prototype? Which properties are stored in which objects (text, toString and code)?
Upvotes: 0
Views: 32
Reputation: 370729
Both constructors, when run, have a this
which is the new instance being constructed. So, the lines
this.text = text;
and
this.code = code;
both put a property directly on the instance.
You can see this if you check hasOwnProperty
:
class Message {
constructor(text) {
this.text = text;
}
toString() {
return this.text;
}
}
class ErrorMessage extends Message {
constructor(text, code) {
super(text);
this.code = code;
}
}
const m = new ErrorMessage();
console.log(
m.hasOwnProperty('text'),
m.hasOwnProperty('code')
);
toString
is a normal method on Message.prototype
. This means that the instance (assuming you're creating an ErrorMessage
) inherits this property via ErrorMessage.prototype
, since it inherits from Message.prototype
. The internal prototype chain is:
instance <- ErrorMessage.prototype <- Message.prototype <- Object.prototype
Upvotes: 2