0
我在调用递归函数,并且想要将从递归调用接收到的错误连接回调用方。以下是我使用的代码。但是,它看起来像_errors变量在我的实例之间共享。我怎样才能使这个_errors变量对于实例是唯一的。跨实例共享的Javascript变量
var check = require('./validator.js').check;
var QV = function() {
this._errors = {};
}
QV.prototype.a = function (str) { check(str).len(1,4).notNull().isInt() };
QV.prototype.b = function (str) { check(str).len(1,4).notNull().isInt() };
QV.prototype.c = function (str) { check(str).len(1,4).notNull().isInt() };
QV.prototype.validator = function (opt) {
qv = new QV();
for(var i in opt) {
try {
if (opt[i].toString() === '[object Object]')
{
var errors = qv.validator(opt[i]);
console.log(qv._errors); //Here the qv._errors is overwritten with the 'sub' errors. I lose the error 'a' here.
qv._errors[i] = errors;
}
else
{
qv[i](opt[i]);
}
} catch (e) {
qv._errors[i] = e;
}
}
return qv._errors;
}
module.exports = QV;
而且我用这个代码做验证
var test = require('./test_validator.js');
var q = new test();
msg = q.validator({
'a' : "asdf",
'sub' : {
'b' : "asdf",
'c' : "bsdf"
}
});
console.log(msg);
用'var'声明“qv”!目前它是一个全球变量;换句话说,只有一个“qv”。 – Pointy
太好了。有用。即使我在没有var的情况下声明它,并且即使我将该名称更改为qvx,它也不会抛出任何错误。不管怎样,一旦我将它声明为var,它就可以工作。谢谢! – John