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

看板Ajax作者 (★閃亮數學推理★)時間17年前 (2008/09/10 20:47), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串4/5 (看更多)
謝謝您的指點 果然一點就中我的問題之所在 當 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 test = new Test(); test.setup(); 這時候原先設定在 test.GetKey() 裡的 this 給 document.onkeypress 執行時 他是指向document 而非我所想的test 所以也就造成 先前所提無法對test.key做任何改變 不過解決方法還在思考 .... 但先謝謝 ※ 引述《TonyQ (沉默是金)》之銘言: : ※ 引述《ckaha (★閃亮數學推理★)》之銘言: : : 由於JS在實做class時 似乎是沒有static的 : : 所以不知道各位是怎麼處理這個問題 : : 但事實上如果這在C++ 我可以用static解決掉他 : : 不知道是某有人遇到同樣的問題呢? : : 以下是全部的code : : http://ntuaha.myweb.hinet.net/test4.html : : 這是還有問題的版本 : : http://ntuaha.myweb.hinet.net/test3.html : : 這是沒有問題 但只是用一般方式處理的 : 你的環境弄的太複雜了 , 這樣很難一一解釋 , : 先弄出一個單純且能突顯出問題點的環境再問吧 . : 我猜或許只是對 this 指向的對象瞭解不夠而已. : javascript中要能比擬類別共享成員的 , prototype應該是正解才是. : 另外既然你都寫了 Snack.prototype.ChangeKey , : 為什麼不寫個 Snack.prototype.getKey 來簡化這個問題? :p -- Every thing can be wrong unless you can proof it is true. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 125.225.131.86
文章代碼(AID): #18ny7Np3 (Ajax)
文章代碼(AID): #18ny7Np3 (Ajax)