作者folio (function(){})()
看板Ajax
标题Re: [问题] 为何FF无法藉由new Function()传递事件?
时间Wed Jan 16 00:24:18 2013
1F:→ StarTouching:我找到问题了 Fx要把event当作function参数 01/15 18:47
2F:→ StarTouching:i.e. Function("event", "if(keyVerify(event)")...) 01/15 18:48
3F:→ StarTouching:不过还是没搞懂 正在思索中... 01/15 18:49
4F:→ StarTouching:我想最好的解释是 匿名函式必须传递event参数 01/15 18:51
5F:→ StarTouching:内部不会自动获得event 01/15 18:52
6F:→ StarTouching:所以说 IE和Chrome能执行 应该都是因为window.event 01/15 18:53
7F:→ StarTouching:另外像html onclick=後面的部分自动就会有event传入 01/15 18:57
8F:→ StarTouching:主要差异在这里 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
9F:推 mrbigmouth:推专业 01/17 11:55