鍍金池/ 問(wèn)答/HTML/ 關(guān)于構(gòu)造函數(shù)的問(wèn)題

關(guān)于構(gòu)造函數(shù)的問(wèn)題

function Parent() {

}

Parent.prototype.func1 = function(callback) {
    this.callback = callback;
}
Parent.prototype.func2 = function() {
    this.callback.fetchData()
}

在構(gòu)造函數(shù)中,是不是func1定義的屬性,如this.callback。在func2中也可以訪問(wèn)?

回答
編輯回答
不舍棄

@Captain @Just_do 為什么在chrome里斷點(diǎn)調(diào)試看到this指向的是構(gòu)造函數(shù)Parent
圖片描述

經(jīng)過(guò)chrome斷點(diǎn)測(cè)試,并不是因?yàn)闆](méi)有先new Parent()實(shí)例化導(dǎo)致this指向Parent。構(gòu)造函數(shù)的prototype的屬性上,this都是指的Parent。。。。。。(做個(gè)備注,方便下次查看)

2017年6月19日 22:45
編輯回答
尤禮

可以 構(gòu)造函數(shù)中的this是實(shí)例對(duì)象,這些屬性是掛在實(shí)例對(duì)象上的。

function Parent() {

}

Parent.prototype.func1 = function(callback) {
    this.callback = callback;
}
Parent.prototype.func2 = function() {
  console.log(this.callback)
    this.callback.fetchData()
}



Parent.prototype.func1({fetchData: function(){
    console.log(2)
}})

let per = new Parent()
per.func2()

clipboard.png

2017年1月23日 19:11
編輯回答
汐顏

實(shí)例化后,使用獲得的對(duì)象執(zhí)行一次func1,該對(duì)象中調(diào)用func2時(shí)就可以訪問(wèn)thi.callback了

2018年5月25日 09:46
編輯回答
骨殘心

是的,原型和構(gòu)造函數(shù)中的this指向的都是將來(lái)要?jiǎng)?chuàng)建的實(shí)例

2017年4月15日 19:48