简体   繁体   English

功能范围问题,并转换为箭头功能

[英]Scoping issue with functions and convert to Arrow Functions

I'm learning how to work with arrow functions and I've tried to convert my code below. 我正在学习如何使用箭头功能,并且尝试在下面转换我的代码。 There are a scope problem with funcCall and enterKey. funcCall和enterKey存在作用域问题。 I belive that an arrow function should solve this. 我相信箭头功能应该可以解决这个问题。

function pressKey(funcCall, enterKey = 13) {
    document.addEventListener("keydown", _onKeyDown);
}
function _onKeyDown(e) {
    if(e.keyCode === enterKey) {
        e.preventDefault();
        funcCall();
    }
}

You need to create _onKeyDown inside the scope of pressKey so that it has access to funcCall and enterKey via closure: 您需要创建_onKeyDown的范围内pressKey ,这样它可以访问funcCallenterKey通过关闭:

function pressKey(funcCall, enterKey = 13) {
    function _onKeyDown(e) {
        if(e.keyCode === enterKey) {
            e.preventDefault();
            funcCall();
        }
    }
    document.addEventListener("keydown", _onKeyDown);
}

Using arrow functions or not shouldn't matter for that. 是否使用箭头功能无关紧要。

What you want is a closure from partial application, and yes, arrow functions are good for accomplishing this concisely: 您想要的是关闭部分应用程序,是的,箭头功能可以很好地完成此操作:

const _onKeyDown = (funcCall, enterKey) => e => {
    if (e.keyCode === enterKey) {
        e.preventDefault();
        funcCall();
    }
};

function pressKey(funcCall, enterKey = 13) {
    document.addEventListener("keydown", _onKeyDown(funcCall, enterKey));
}

However, as is pointed out by others, this feature is not exclusive to arrow functions, so if you enjoy typing or are stuck without ECMAScript 2015 syntax: 但是,正如其他人指出的那样,此功能不是箭头功能所独有的,因此,如果您喜欢打字或不使用ECMAScript 2015语法而感到困惑:

function _onKeyDown(funcCall, enterKey) {
    return function (e) {
        if (e.keyCode === enterKey) {
            e.preventDefault();
            funcCall();
        }
    };
}

function pressKey(funcCall, enterKey = 13) {
    document.addEventListener("keydown", _onKeyDown(funcCall, enterKey));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM