作者No (you stay there)
看板Ajax
標題Re: [問題] 獲取上一級物件屬性
時間Thu Oct 18 14:45:20 2012
※ 引述《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
1F:推 Ju1ien:感謝! 10/18 15:22