Question

I'm calling a recursive function and I want to concatenate the errors received from the recursive call back to the caller. Following is the code, I use. However, it looks like the _errors variable is shared between my instances. How can I make this _errors variable unique to the instances.

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;

And I use this code to do the validation

var test = require('./test_validator.js');
var q = new test();

msg = q.validator({
    'a' : "asdf",
    'sub' : {
        'b' : "asdf",
        'c' : "bsdf"
    }
});
console.log(msg);
Was it helpful?

Solution

The answer is already in the comments. I suggest you to the following

1) Use Javascript "strict" mode - it will make modern browsers to convert mistakes like this to errors https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/Strict_mode

2) Use jshint against your script - it will prevent errors like this http://jshint.com/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top