javascript - 来自外部范围的 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
};
我想在电子邮件的验证功能中使用电子邮件(电子邮件)功能,但我有可变阴影,我该如何实现?
解决方案
您不能直接访问阴影变量。除非您对该值有其他处理方式。
最好的解决方案就是不要阴影。
或者,更改您的电子邮件地址变量的名称:
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 函数分配给了另一个对象,我们仍然可以访问它。
有很多方法可以做到这一点,具体取决于您如何构建代码库。
但是,一般来说,阴影是不好的,你应该尽量避免它。
推荐阅读
- android - 未能获取平台 cordova-browser@ 5.0.1
- python-3.x - 使用 pyzbar 检查校正 QR 码扫描仪
- arrays - 基于另一个数组过滤打字稿数组
- elasticsearch - 无法在弹性搜索中编组域实例 [demo.Category : 7]
- sql - Sql Query 问题(从一个表随机添加值到另一个表)
- java - Java 中的 Base64 指南
- merge - NodeGit fileHistoryWalk 不显示合并提交
- python - 如何根据值将python字典拆分为多个字典
- python - 使用 Python.Net 导入具有依赖项的 .NET Standard 2.0 类库
- r - 提取由'rfm'包生成的RFM结果 - R