在函数中向函数对象添加属性有哪些缺陷?(What are the pitfalls of adding properties to a function object within the funct

编程入门 行业动态 更新时间:2024-10-26 05:27:15
函数中向函数对象添加属性有哪些缺陷?(What are the pitfalls of adding properties to a function object within the function?)

我发现我可以使用这种技术在事件处理程序中保留一种“状态”,而不必涉及外部变量......

我发现这种技术在利用函数实际上是对象本身这一事实时非常聪明,但我担心我正在做一些可能会产生负面影响的事情......

例...

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.

更多推荐

本文发布于:2023-07-29 14:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1316767.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   缺陷   中向   属性   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!