2013-01-20 100 views
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); 
+1

用'var'聲明「qv」!目前它是一個全球變量;換句話說,只有一個「qv」。 – Pointy

+0

太好了。有用。即使我在沒有var的情況下聲明它,並且即使我將該名稱更改爲qvx,它也不會拋出任何錯誤。不管怎樣,一旦我將它聲明爲var,它就可以工作。謝謝! – John

回答