【问题标题】:Which properties are stored in which object in Javascript prototyping?Javascript原型中哪些属性存储在哪个对象中?
【发布时间】:2020-06-23 03:45:26
【问题描述】:
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 和代码)中?

【问题讨论】:

    标签: javascript inheritance prototype chain


    【解决方案1】:

    两个构造函数在运行时都有一个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')
    );

    toStringMessage.prototype 上的普通方法。这意味着实例(假设您正在创建ErrorMessage)通过ErrorMessage.prototype 继承此属性,因为it 继承自Message.prototype。内部原型链是:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2016-02-26
      • 2014-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多