Re: [問題] 獲取上一級物件屬性

看板Ajax作者 (you stay there)時間13年前 (2012/10/18 14:45), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《Ju1ien (Julien)》之銘言: : //下面是問題 : function TTest(){ : this.v=2; : this.subObj=new Object(); : this.subObj.m=TTestM; : } : function TTestM(){ : alert(this.v); : } : var t=new TTest(); : t.subObj.m(); : //這裡this.v就不對了,問題就是: 在subObj的函式m()裡 : //能不能獲取物件t的屬性v﹐不知道有沒有講清楚 : //感謝! this的繫結比較晚 發生在function被呼叫的時候 並依呼叫的方式決定繫結對象 而以物件方法呼叫時 this繫結到呼叫方法的物件本身 以你的程式來看 this繫結到subObj 要獲取上層沒有native的方式 但可以在建立subObj的時候自訂parent把this帶進去 function TTest() { this.v = 2; this.subObj = {}; this.subObj.parent = this; this.subObj.m = TTestM; } function TTestM() { alert(this.parent.v); } var t = new TTest(); t.subObj.m(); -- ▂▁ ▄▄▄▄ 程式寫到鬼打牆? ψ 贛! xx▄▄▄▄▄ 快上 http://ghosthitswall.com/ ▉⊙ xxx xxxxxxx ▋│xx* xxxxxxx ⊙-⊙ 這該死的BUG!!! Φ ◣ ◢xxx xxxxxxx - ˊ ▃▅▇▅▃  ̄ ̄╩@__ ◣◣◣◣ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 1.165.195.39

10/18 15:22, , 1F
感謝!
10/18 15:22, 1F
文章代碼(AID): #1GVwMAcK (Ajax)
討論串 (同標題文章)
文章代碼(AID): #1GVwMAcK (Ajax)