Re: [問題] 關於JS在實做class的手法
謝謝您的指點 果然一點就中我的問題之所在
當
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
討論串 (同標題文章)
Ajax 近期熱門文章
PTT數位生活區 即時熱門文章