首先用一個例子指出來constructor存在形式,
function Fruit(){ } var f=new Fruit(); console.log(f.constructor);//列印出Fruit()
由上面的代碼我們總結出結論1:上面的代碼在控制臺可以看出constructor是指向構造器Fruit的參考,
function Fruit(){ this.name="水果"} //var f=new Fruit(); function Apple(){this.name="蘋果";} Apple.prototype=new Fruit(); var apple=new Apple(); console.log(apple.constructor);//依然列印出Fruit() Apple.prototype={};//空物件的構造器是Object() apple=new Apple(); console.log(apple.constructor);//指向Object()
這個地方就有點奇怪了,這個constructor到底指向的是那個實體的構造器?
根據上面的代碼總結出結論2:constructor指向的是原型物件的構造器的參考
即 apple.constructor==Apple.prototype.constructor
var apple2=new apple.constructor(); console.log(apple2.name);
或者
var apple2=new Apple.prototype.constructor(); console.log(apple2.name);
列印的都是水果,
我們現在想讓他執行的是蘋果的列印;這個時候就需要對constructor的指向進行重新指定,
根據上面的兩個結論:無論是修改實體的constructor還是構造器的原型constructor屬性都是可以達到目的的;
可以在重寫了prototype屬性的代碼后寫下這樣的代碼
Apple.prototype.constructor=Apple;
或者在實體化后對實體的constructor進行重新制定,
apple.constructor=Apple;
雖然上面的兩種方式都能達到目的,但是推薦使用第一種,
第二種方式需要有一個實體化的物件,而我們只用在對繼承的創建完成后才會去實體化,
等有了實體化物件在去修改constructor,這個時候已經遲了,意義已經不大了,繼承的關系已經確定了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/125526.html
標籤:其他
上一篇:JS---案例:高清放大鏡
