作者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