Re: [問題] 獲取上一級物件屬性
※ 引述《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/
h 肝◤ ▉⊙ ⊙▍◥│xxx xxxxxxx │ ◢ ◣
t │ 工▎ ◤皿◥ ▋│xx* xxxxxxx │ ∴ ⊙-⊙ 這該死的BUG!!!
x Φ 程◣ ◣ ◢ ◤│xxx xxxxxxx │入○- 皿 ○ ˊ
9 │ 師 ◣▃▅▇▅▃◢◢  ̄ ̄╩@╮◤ ▊__ ◣◣◣◣
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 1.165.195.39
推
10/18 15:22, , 1F
10/18 15:22, 1F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
Ajax 近期熱門文章
PTT數位生活區 即時熱門文章
6
12
-16
33