在函数内向函数对象添加属性有哪些陷阱?

发布于 2024-12-06 22:40:51 字数 575 浏览 1 评论 0原文

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

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

示例...

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧瑾黎汐 2024-12-13 22:40:51

您可以使用闭包来代替这样做:

element.onclick = (function() {
  var count = 0;
  return function(ev) {
    count++;
    if (count === 3) {
      alert("3");
      count = 0;
    }
  };
})();

该设置涉及代码立即调用的匿名函数。该函数有一个局部变量“count”,它将在连续的事件处理程序调用中保留。

顺便说一句, this:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文