首页 > 解决方案 > 来自外部范围的 Javascript 函数

问题描述

嘿伙计们,我是 JavaScript 新手,我有一个问题。我有 validator.js 文件,我在其中验证电子邮件、密码和请求。就这个

/**
 * Simple regex validator for email
 * @param email The email
 * @returns {boolean} Whether the email matches the regex
 */
function email(email) {
    const regExp = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return regExp.test(email);

}

/**
 * Simple regex validator for password
 * @param password The password
 * @returns {boolean} Whether the password matches the regex
 */
function password(password) {
    const regExp = /^(?=.*\d).{7,15}$/;
    return regExp.test(password);
}

const request = {
    email: {
        message: '',
        validate: function (req) {
            const email = req.body.email;
            if(!email){
                email.message = 'Email is required';
                return false;
            }
            if(!validator(email(email))){
                email.message = 'Email is not valid';
                return false;
            }
            return true;
        }
    }
};

module.exports = {
    email,
    password,
    request
};

我想在电子邮件的验证功能中使用电子邮件(电子邮件)功能,但我有可变阴影,我该如何实现?

标签: javascriptvariablesscopeshadow

解决方案


您不能直接访问阴影变量。除非您对该值有其他处理方式。

最好的解决方案就是不要阴影。

或者,更改您的电子邮件地址变量的名称:

const emailAddress = req.body.email;

或者更改您的电子邮件验证功能的名称:

function validateEmail(email) {

或者更好的是,为了清楚起见,两者都做。


这就是我所说的“其他手柄”的意思。

function email(email) { /* ... */ }
function password(password) { /* ... */ }

const validators = { email, password }

function doStuff() {
  const email = req.body.email;
  validators.email(email)
}

在这种情况下,我们隐藏了局部变量email,但是我们将 email 函数分配给了另一个对象,我们仍然可以访问它。

有很多方法可以做到这一点,具体取决于您如何构建代码库。


但是,一般来说,阴影是不好的,你应该尽量避免它。


推荐阅读