私有成员——跨实例共享的Javascript变量

private members - Javascript variable shared across instances

本文关键字:Javascript 变量 共享 成员 实例      更新时间:2023-09-26

我正在调用一个递归函数,我想将从递归调用收到的错误连接回调用者。下面是我使用的代码。然而,看起来_errors变量在实例之间是共享的。我怎样才能使这个_errors变量对实例来说是唯一的呢?

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);

答案已经在评论里了。我建议你做以下事情

1)使用Javascript的"严格"模式-它会使现代浏览器将这样的错误转换为错误https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/Strict_mode

2)对脚本使用jshint -它将防止类似这样的错误http://jshint.com/