作者TonyQ (沉默是金)
看板Ajax
標題Re: [問題] 關於JS在實做class的手法
時間Wed Sep 10 21:02:44 2008
※ 引述《ckaha (★閃亮數學推理★)》之銘言:
: 謝謝您的指點 果然一點就中我的問題之所在
: 當
: function Test() {
: this.key = 0;
: this.GO = function(){ alert(this.key); .... };
: this.GetKey = function(){ this.key = 2; } }; (*)
: this.setup = function() {
: document.onkeypress = this.GetKey(); <---------這步
var _this=this; //保留當前物件的參考.
document.onkeypress = function(){
this.GetKey.apply(_this);
}
: }
: }
: var test = new Test();
: test.setup();
: 但先謝謝
試試看apply(委讓) 這個function的原生prototype ,
他可以改變function 中, this指向的對象.
ex.
function ckThis(){
alert(this);
}
ckThis.apply(['hi1']);
ckThis.apply(['hi2']);
ckThis();
http://tony1223.no-ip.org:81/test/testApply.html
this 的確是常常一不小心就會誤用 , 而且難以檢驗.
--
What do you want to have ? / What do you have?
從書本中,你可以發現我的各種興趣。
從CD中,你可以瞭解我所喜歡的偶像明星。
或許從文字你很難以瞭解一個人,但從物品可以。
My PPolis , My past. http://ppolis.tw/user/Tony
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 59.104.41.124
1F:推 ckaha:WA 好方法 謝謝 09/10 21:04
2F:推 ckaha:成功了~~謝謝 09/10 21:11
3F:推 todau:推tony的方式,這是利用closure的好方式。不過,我記得是用 09/11 15:16
4F:→ todau:ckThis.call() 而不是 ckThis.apply() 的樣子? 09/11 15:16
5F:→ TonyQ:有一些些細微的差異, apply可搭配 arguments 原生物件更好. 09/11 15:19
7F:→ TonyQ:主要是除了呼叫函數之外 , 也可以傳參數進去. 09/11 15:19
8F:→ TonyQ:當然單就這個例子來講 , call跟apply是都可以用的. :) 09/11 15:19
9F:→ TonyQ:關於 arguments 物件的介紹看這篇 09/11 15:21
※ 編輯: TonyQ 來自: 220.128.219.202 (09/11 15:23)