在Javascript中重置原型。为什么它会破坏原型继承链?
我有以下代码:在Javascript中重置原型。为什么它会破坏原型继承链?,javascript,prototype,Javascript,Prototype,我有以下代码: 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(Prin
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
是运算符,而不是方法。你写的是1+(2)
printsuff.prototype
不是printsuff
的原型;它是由PrintStuff
构造函数创建的对象的原型。替换它时,在此之后创建的任何对象将不再具有.print
方法<代码>打印机仍然如此,因为它仍然拥有旧的原型printer
)的原型链(旧的PrintStuff.prototype
)中是否有构造函数的原型属性(新的PrintStuff.prototype
,或{}
)。“由于两者明显不同,instanceof
返回false
instanceof
是运算符,而不是方法。你写的是1+(2)
printsuff.prototype
不是printsuff
的原型;它是由PrintStuff
构造函数创建的对象的原型。替换它时,在此之后创建的任何对象将不再具有.print
方法<代码>打印机仍然如此,因为它仍然拥有旧的原型printer
)的原型链(旧的PrintStuff.prototype
)中是否有构造函数的原型属性(新的PrintStuff.prototype
,或{}
)。“由于两者明显不同,instanceof
返回false
instanceof
是运算符,而不是方法。你写的是1+(2)
printsuff.prototype
不是printsuff
的原型;它是由PrintStuff
构造函数创建的对象的原型。替换它时,在此之后创建的任何对象将不再具有.print
方法<代码>打印机仍然如此,因为它仍然拥有旧的原型printer
)的原型链(旧的PrintStuff.prototype
)中是否有构造函数的原型属性(新的PrintStuff.prototype
,或{}
)。“由于两者明显不同,instanceof
返回false
instanceof
是运算符,而不是方法。你写的是1+(2)
printsuff.prototype
不是printsuff
的原型;它是由PrintStuff
构造函数创建的对象的原型。替换它时,在此之后创建的任何对象将不再具有.print
方法<代码>打印机仍然如此,因为它仍然拥有旧的原型printer
)的原型链(旧的PrintStuff.prototype
)中是否有构造函数的原型属性(新的PrintStuff.prototype
,或{}
)。“由于两者明显不同,instanceof
返回false
instanceof是JavaScript操作符-它检查被检查对象的原型链中是否存在函数(构造函数)的原型对象 使用new创建对象时,javascript将对象的内部原型设置为链接到新函数的原型对象。当您将新的d函数更改为具有不同的原型对象时,原始创建的对象仍然链接到新的d函数的原始原型对象 (在Chrome中),您可以访问对象的内部原型链接,因此可以通过执行
PrintStuff.prototype=printer.\uuuuu proto\uuuu
将其反转,如果这样可以更好地了解正在发生的事情
你所说的“逆转”是什么意思?
最初,创建PrintStuff函数时,PrintStuff对象链接到其原型,如下所示:
[PrintStuff] --- prototype ---> [PrintStuffPrototype]
执行此操作时:PrintStuff.prototype={}
您将得到:
[PrintStuff] -link lost- [PrintStuffPrototype]
`.
`---- prototype ---> {}
PrintStuffPrototype对象挂起在内存中。反转它意味着将原始PrintStuff prototype重新链接到PrintStuff函数。instanceof是JavaScript运算符-它检查被检查对象的prototype链中是否存在函数(构造函数)的prototype对象 使用new创建对象时,javascript将对象的内部原型设置为链接到新函数的原型对象。当您将新的d函数更改为具有不同的原型对象时,原始创建的对象仍然链接到新的d函数的原始原型对象 (在Chrome中),您可以访问对象的内部原型链接,因此可以通过执行
PrintStuff.prototype=printer.\uuuuu proto\uuuu
将其反转,如果这样可以更好地了解正在发生的事情
你所说的“逆转”是什么意思?
最初,创建PrintStuff函数时,PrintStuff对象链接到其原型,如下所示:
[PrintStuff] --- prototype ---> [PrintStuffPrototype]
执行此操作时:PrintStuff.prototype={}
您将得到:
[PrintStuff] -link lost- [PrintStuffPrototype]
`.
`---- prototype ---> {}
PrintStuffPrototype对象挂起在内存中。反转它意味着将原始PrintStuff prototype重新链接到PrintStuff函数。instanceof是JavaScript运算符-它检查prot中是否存在函数(构造函数)的prototype对象