2015-10-19 108 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