Re: [問題] 關於JS在實做class的手法

看板Ajax作者 (沉默是金)時間17年前 (2008/09/10 21:02), 編輯推噓3(307)
留言10則, 3人參與, 最新討論串5/5 (看更多)
※ 引述《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

09/10 21:04, , 1F
WA 好方法 謝謝
09/10 21:04, 1F

09/10 21:11, , 2F
成功了~~謝謝
09/10 21:11, 2F

09/11 15:16, , 3F
推tony的方式,這是利用closure的好方式。不過,我記得是用
09/11 15:16, 3F

09/11 15:16, , 4F
ckThis.call() 而不是 ckThis.apply() 的樣子?
09/11 15:16, 4F

09/11 15:19, , 5F
有一些些細微的差異, apply可搭配 arguments 原生物件更好.
09/11 15:19, 5F

09/11 15:19, , 7F
主要是除了呼叫函數之外 , 也可以傳參數進去.
09/11 15:19, 7F

09/11 15:19, , 8F
當然單就這個例子來講 , call跟apply是都可以用的. :)
09/11 15:19, 8F

09/11 15:21, , 9F
關於 arguments 物件的介紹看這篇
09/11 15:21, 9F

09/11 15:21, , 10F
09/11 15:21, 10F
※ 編輯: TonyQ 來自: 220.128.219.202 (09/11 15:23)
文章代碼(AID): #18nyLs3s (Ajax)
文章代碼(AID): #18nyLs3s (Ajax)