Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript OOP继承创建全局对象_Javascript_Oop_Global_Extend - Fatal编程技术网

Javascript OOP继承创建全局对象

Javascript OOP继承创建全局对象,javascript,oop,global,extend,Javascript,Oop,Global,Extend,看那个 // @alias ActiveRecord.extend ... extend: function extend(destination, source){ for (var property in source){ destination[property] = source[property]; } return destination; } ... 我有这门课: function Exception(){} Exception.prototype

看那个

// @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]}
我怎样才能解决这个问题


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

问题在于您的
异常
类:

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.m
this.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 ?
    }
}

我不确定console.log(a.errors.messages)将如何显示任何内容,因为您没有更改errors对象中的messages对象。您能展示整个代码吗?您如何构造
验证
对象?答案是正确的,消息来自Exception.prototype,并在异常实例之间共享。如果您在一个实例上变异原型成员,它将在所有实例上更改此成员。以下答案可能有助于您理解特定于实例的原型成员和阴影: