在函数内向函数对象添加属性有哪些陷阱?
我发现我可以使用这种技术在事件处理程序中保留某种“状态”,而无需涉及外部变量...
我发现这种技术非常聪明地利用了函数实际上是的事实对象本身,但担心我正在做的事情可能会产生某种负面影响...
示例...
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;
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用闭包来代替这样做:
该设置涉及代码立即调用的匿名函数。该函数有一个局部变量“count”,它将在连续的事件处理程序调用中保留。
顺便说一句, this:
是“危险的”,因为当你在函数表达式中包含一个名称时,某些浏览器(猜猜是不是,尽管 Safari 也有问题)会做出奇怪的事情。 Kangax 非常彻底地写了这个问题。
Instead of doing that, you can use a closure:
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:
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.