我发现我可以使用这种技术在事件处理程序中保留一种“状态”,而不必涉及外部变量......
我发现这种技术在利用函数实际上是对象本身这一事实时非常聪明,但我担心我正在做一些可能会产生负面影响的事情......
例...
var element = document.getElementById('button'); element.onclick = function funcName() { // attaching properties to the internally named "funcName" funcName.count = funcName.count || 0; funcName.count++; if (self.count === 3) { // do something every third time alert("Third time's the charm!"); //reset counter funcName.count = 0; } };I found I could use this technique to retain a sort of "state" within an event handler, w/o having to involve outside variables...
I find this technique to be very clever in leveraging the fact that functions are actually objects in and of themselves, but am worried I'm doing something that could have negative implications of some sort...
Example...
var element = document.getElementById('button'); element.onclick = function funcName() { // attaching properties to the internally named "funcName" funcName.count = funcName.count || 0; funcName.count++; if (self.count === 3) { // do something every third time alert("Third time's the charm!"); //reset counter funcName.count = 0; } };最满意答案
而不是这样做,你可以使用一个闭包:
element.onclick = (function() { var count = 0; return function(ev) { count++; if (count === 3) { alert("3"); count = 0; } }; })();该设置涉及代码立即调用的匿名函数。 该函数有一个局部变量“count”,它将在一系列事件处理程序调用中保留。
顺便说一下,这个:
var something = function dangerous() { ... };是“危险的”,因为有些浏览器(猜测哪些,虽然Safari也有问题)当你在这样的函数表达式中包含一个名称时会做一些奇怪的事情。 Kangax非常彻底地写了这个问题。
Instead of doing that, you can use a closure:
element.onclick = (function() { var count = 0; return function(ev) { count++; if (count === 3) { alert("3"); count = 0; } }; })();That setup involves an anonymous function that the code immediately calls. That function has a local variable, "count", which will be preserved over the succession of event handler calls.
By the way, this:
var something = function dangerous() { ... };is "dangerous" because some browsers (guess which, though Safari has had issues too) do weird things when you include a name on a function expression like that. Kangax wrote the issue up quite thoroughly.
更多推荐
发布评论