在Javascript原型中,哪些属性存储在哪个对象中


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);

原型究竟是什么,假设我们调用:ErrorMessage.prototype或Message.prototype?哪些属性存储在哪些对象中(文本、toString和代码(?

运行时,两个构造函数都有一个this,它是正在构建的新实例。因此,线路

this.text = text;

this.code = code;

两者都直接在实例上放置了一个属性。

如果你检查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')
);

CCD_ 4是CCD_。这意味着实例(假设您正在创建ErrorMessage(通过ErrorMessage.prototype继承此属性,因为继承自Message.prototype。内部原型链是:

instance <- ErrorMessage.prototype <- Message.prototype <- Object.prototype

最新更新