替代arguments.callee的 [英] Alternative to arguments.callee

查看:264
本文介绍了替代arguments.callee的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的的EventListener 的侦听到整个文件和记录击键,但我想在满足一定条件下删除该监听器。

I have an EventListener that listens to the entire document and records keystrokes, but I want to remove this Listener when certain conditions are met.

以下是我的code的一个片段:

The following is a snippet of my code:

document.addEventListener('keyup', function(e) {
    var letter_entered = String.fromCharCode(e.keyCode).toLowerCase();
    player.makeGuess(letter_entered);

    if(player.win_status === true || player.lose_status === true) {
        document.removeEventListener('keyup', arguments.callee, false);
    }
});

这工作,但根据<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments/callee\"相对=nofollow> Mozilla开发者文档这种方法已经去precated。

This works, however according to the Mozilla Developer Docs this method has been deprecated.

我知道,我可以简单地命名的功能,但有,让我继续使用匿名函数替代

I'm aware that I can simply name the function, but is there an alternative that would allow me to continue using the unnamed function?

推荐答案

使用以下过程:


  • 创建一个变量

  • 分配一个匿名函数变量

  • 的变量引用调用它

  • 使用变量名匿名函数引用自身

使用它作为这样的:

   var foo = function(e)
    {
    "use strict";
    console.log(e);
    document.removeEventListener('keyup', foo, false);
    }

document.addEventListener('keyup', foo);

您可以轻松地使用ÿ解决这个问题组合子:

You can solve this problem easily using the y combinator:

function y(f) {
    return function () {
        return f.bind(null, y(f)).apply(this, arguments);
    };
}

现在可以通过改写code如下:

Now you can rewrite your code as follows:

document.addEventListener("keyup", y(function (callee, e) {
    player.makeGuess(String.fromCharCode(e.keyCode).toLowerCase());
    if (player.win_status || player.lose_status) document
        .removeEventListener("keyup", callee);
}));

这是所有乡亲。

这篇关于替代arguments.callee的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆