我有这个代码:
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
- instanceof 是什么样的方法?为什么没有在对象上调用它?
- 为什么设置 PrintStuff 的原型(prototype)会破坏打印机对象的继承链?
最佳答案
instanceof
是一个运算符,而不是一个方法。你写的就像1 +(2)
。PrintStuff.prototype
不是PrintStuff
的原型(prototype);它是由PrintStuff
构造函数创建的对象的原型(prototype)。当您替换它时,此后创建的任何对象将不再具有.print
方法。printer
仍然如此,因为它仍然具有旧的原型(prototype)。(1+2,真的):正如 MDN 所说,instanceof 运算符测试对象(
printer
)是否在其原型(prototype)链中(旧的PrintStuff.prototype
) 构造函数的原型(prototype)属性(newPrintStuff.prototype
或{}
)。”由于两者明显不同,instanceof
返回false
。
关于javascript - 在 Javascript 中重置原型(prototype)。为什么会破坏原型(prototype)继承链呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33206962/