2015-10-19 61 views
0

我有这样的代码:重置Javascript中的原型。为什么它会破坏原型继承链?

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的原型会销毁打印机对象的继承链?

回答

1

的instanceof是JavaScript的操作员 - 它检查在对象的原型链中是否存在函数(构造)的原型对象被检查

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

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

你是什么意思“逆转”?

最初,当你创建PrintStuff功能,PrintStuff对象链接到它的原型,像这样:

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

当你这样做:PrintStuff.prototype = {}你:

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

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

+0

太棒了,但是你的意思是“逆转它”呢? – Jwan622

+1

@ Jwan622指我的编辑 – sahbeewah

2
  1. instanceof是一个操作符,而不是一个方法。你写的东西就像1 +(2)

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

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