Javascript OOP 继承了 create GLOBAL 对象

Javascript OOP inherits create GLOBAL object

本文关键字:GLOBAL 对象 create OOP 继承 Javascript      更新时间:2023-09-26

看。

// @alias ActiveRecord.extend
...
extend: function extend(destination, source){
   for (var property in source){
       destination[property] = source[property];
   }
   return destination;
}
...

我有这个类:

function Exception(){}
Exception.prototype = {
    messages: {},
    add: function(k, v){
          if(!Array.isArray(this.messages[k])) this.messages[k] = new Array
          this.messages[k].push(v)
    }
}

而且,我有这个课程。它在方法this.errors中调用一个新的异常。

function Validations(){
   this.errors = new Exception
}
而且,我创建了这个模型,模型有验证,

验证有错误,很好。

ActiveSupport.extend(Model.prototype, Validations.prototype)
function Model(){};

但。。。当我创建一个新实例作为模型并向该实例添加错误时,类异常显示为全局对象。看。。。

a = new Model
a.errors.add('a', 1);
console.log(a.errors.messages) // return {a: [1]}
b = new Model
b.errors.add('a', 2);
console.log(b.errors.messages) // return {a: [1,2]}

我该如何解决这个问题?

如何使类异常的消息数组不是全局的?

问题出在Exception类上:

function Exception(){}
Exception.prototype = {
    messages: {},
    add: function(k, v){
          if(!Array.isArray(this.m[k])) this.m[k] = new Array
          this.m[k].push(v)
          // did you mean this.messages ?
    }
}

我认为this.mthis.messages应该是一回事,所以我会把它当作这样对待。


您的messages对象与异常原型相关联。这意味着它会在所有实例之间共享。现在这是一个非常简单的修复:只需将其放入启动中即可。

function Exception(){
    this.messages = {};
}
Exception.prototype = {
    add: function(k, v){
          if(!Array.isArray(this.m[k])) this.m[k] = new Array
          this.m[k].push(v)
          // did you mean this.messages ?
    }
}