【问题标题】:Resetting prototypes in Javascript. Why does it destroy the prototype inheritance chain? [duplicate]在 Javascript 中重置原型。为什么会破坏原型继承链? [复制]
【发布时间】:2023-03-25 14:25:01
【问题描述】:

我有这个代码:

function PrintStuff(docs) {
  this.docs = docs;
}

PrintStuff.prototype.print = function() {
  console.log(this.docs)
}

var printer = new PrintStuff("Hello World");
printer.print()
console.log(Object.getPrototypeOf(printer))
console.log(PrintStuff.prototype)
console.log(printer instanceof(PrintStuff))
//true

PrintStuff.prototype = {}
console.log(printer instanceof(PrintStuff))
//false
  1. instanceof 是什么方法?为什么不在对象上调用它?
  2. 为什么设置 PrintStuff 的原型会破坏打印机对象的继承链?

【问题讨论】:

    标签: javascript prototype


    【解决方案1】:
    1. instanceof 是运算符,而不是方法。你写的就像1 +(2)

    2. PrintStuff.prototype 不是PrintStuff 的原型;它是PrintStuff 构造函数创建的对象的原型。当您替换它时,此后创建的任何对象都将不再具有 .print 方法。 printer 仍然存在,因为它仍然有旧原型。

    3. (1+2,真的):正如 MDN 所说,instanceof 运算符测试对象 (printer) 在其原型链(旧 PrintStuff.prototype)中是否具有构造函数的原型属性(新 @ 987654330@,或{})。”由于两者明显不同,instanceof 返回false

    【讨论】:

      【解决方案2】:

      instanceof 是 JavaScript 运算符 - 它检查函数(构造函数)的原型对象是否存在于被检查对象的原型链中。

      当您使用 new 创建对象时,javascript 会将对象的内部原型设置为链接到新函数的原型对象。当您将新函数更改为具有不同的原型对象时,原始创建的对象仍链接到新函数的原始原型对象。

      (在 Chrome 中),您可以访问对象的内部原型链接,因此可以通过执行 PrintStuff.prototype = printer.__proto__ 来反转它,如果这样可以让您更好地了解正在发生的事情。

      “反转”是什么意思?

      最初,当您创建 PrintStuff 函数时,PrintStuff 对象会链接到它的原型,如下所示:

      [PrintStuff] --- prototype ---> [PrintStuffPrototype]
      

      当你这样做时:PrintStuff.prototype = {} 你会得到:

      [PrintStuff] -link lost- [PrintStuffPrototype]
             `.
               `---- prototype ---> {}
      

      PrintStuffPrototype 对象挂在内存中。反转它意味着将原始 PrintStuffPrototype 重新链接到 PrintStuff 函数。

      【讨论】:

      • 太棒了,但你所说的“反转”是什么意思?
      • @Jwan622 参考我的编辑
      猜你喜欢
      • 2019-01-24
      • 2016-07-04
      • 2011-11-09
      • 2020-12-28
      • 2013-02-03
      • 2016-11-19
      • 2016-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多