成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

javascript - 求解答:實例對象調(diào)用constructor,此時constructor內(nèi)的this的指向?

瀏覽:231日期:2023-04-07 11:13:12

問題描述

這個問題其實來自分析jQuery源碼的時候,看到里面使用了var ret = jQuery.merge(this.constructor(), elems );,里面this.constructor()返回的是init方法創(chuàng)建的空的實例對象。因此對其中this的指向產(chǎn)生疑惑。以下為試驗代碼:

function Person() { this.name = ’ddadaa’; console.log(this);}var p1 = new Person();p1.constructor();// Person {name: 'ddadaa'}var p2 = p1.constructor;p2(); //打印的是window

此處為什么直接調(diào)用constructor(),里面的this的指向就發(fā)生了改變,并且自動創(chuàng)建了一個新的對象?是不是constructor()方法的內(nèi)部實現(xiàn)對此有所影響?

問題解答

回答1:

這個和constructor()方法的內(nèi)部實現(xiàn)沒有什么關(guān)系,其實就是函數(shù)內(nèi)this指向的問題。當函數(shù)作為對象的屬性調(diào)用的時候,this指向這個對象;當函數(shù)直接調(diào)用的時候,在非嚴格模式下,this指向window;p1.constructor指向的就是Person函數(shù),當調(diào)用p1.constructor();時,Person是作為p1的屬性調(diào)用的,所以this指向p1;當調(diào)用var p2 = p1.constructor;p2();時,其實就相當于直接調(diào)用Person();,所以this指向window。

標簽: JavaScript