javascript中constructor指向問題


首先用一個例子指出來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,這個時候已經遲了,意義已經不大了,繼承的關系已經確定了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM