Javascript 来自外部作用域的函数

Javascript function from outher scope

大家好,我是 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
};

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

您不能直接访问阴影变量。除非您对该值有其他句柄。

最好的解决办法就是不要阴影。

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

const emailAddress = req.body.email;

或更改电子邮件验证函数的名称:

function validateEmail(email) {

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


我的意思是 "some other handle"。

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

const validators = { email, password }

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

在本例中,我们隐藏了局部变量 email,但我们已将电子邮件功能分配给另一个我们仍然可以访问的对象。

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


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

我也建议这样的解决方案,我认为它更好,因为它概括了请求的正文验证。

const request = {
    body: function(propertyName,func){
        this.message = '';
        this.validate = function(req){
            const propertyValue = req.body[propertyName];
            if(!propertyValue){
                this.message = `${propertyName} is required`
                return false;
            }
            if(!func(propertyValue)){
                this.message = `${propertyName} is not valid`
                return false;
            }
            return true;
        }
    },
};