Re: [問題] 為何FF無法藉由new Function()傳遞事件?
→
01/15 18:47,
01/15 18:47
→
01/15 18:48,
01/15 18:48
→
01/15 18:49,
01/15 18:49
→
01/15 18:51,
01/15 18:51
→
01/15 18:52,
01/15 18:52
→
01/15 18:53,
01/15 18:53
→
01/15 18:57,
01/15 18:57
→
01/15 18:57,
01/15 18:57
- ms dom 中,event 發生時,記載 event data 的 object 放在一個 global variable 裡面,
這個 global variable 叫做 event。
- 而 global variable 其實就是 global object 的某個 property。
- 當我們討論 client-side 的時候 global object 就是 window object。
綜合以上三點,所以 ms dom 中,handler 需要 event data 的時候,會寫 window.event,
事實上你寫 event 也是一樣的意思。
oncilck = Function("if(keyVerify(event)")...)
當 Function constructor 被 evaluate 的時候,是在 global scope 中 evaluate,
而你的 function body 並沒有定義 local 的 event variable,
結果就是拿到 global variable 的 event。
但是在 w3c dom 中並不是把 event data 放在 global variable 裡,
而是作為 handler 的第一個參數傳進 function body。
因此你寫 Function("if(keyVerify(event)")...) 沒有反應是理所當然的,
當你寫 Function("event", "if(keyVerify(event)")...) 的時候,
便定義了第一個參數叫 event,所以在 function body 才可以拿到 event,
小結,ms dom 中 Function("if(keyVerify(event)")...),event 拿到的是 global variable;
w3c dom 中,Function("event", "if(keyVerify(event)")...),event 是 local variable。
所以才會有 TonyQ 提到的 function(event) { event = event || window.event } 的寫法,
這是在說,當 event 這個 local variable 存在的時候,就用這個,
否則就拿 global 的 event variable 來用。
當我們寫 event handler attribute 時,寫的是 function body,
但無論是 ms 或 w3c dom,evaluate event handler attribute 的時候,
都會讓 handler 有一個 event variable 可以用。
在這裡你有幾點我想提一下,如果你知道自己在做什麼請略過。
首先在 javascript 裡面如果是要動態產生 function 的話,並不需要用 Function constructor。
寫 function(){} 就可以了,理由一是 Function constructor 要把 function body 交給
interpreter 處理,這是很昂貴的事情;理由二,這製造了 injection 的時機。
第二 event handler attribute 無法做到 separation of concern,html, css, javascript 這三者,
巧妙的分開了 structure, style and behaviour concerns,
當你在 html 中寫 event handler attribute 時,已經把 structure 跟 behaviour 混在一起了。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 175.180.46.219
推
01/17 11:55, , 1F
01/17 11:55, 1F
討論串 (同標題文章)
Ajax 近期熱門文章
PTT數位生活區 即時熱門文章