0

Look that.

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

I have this class:

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

And, i have this class. And it's call in method this.errors a new Exception.

function Validations(){
   this.errors = new Exception
}

And, i create this Model, the model have validations, the validations have errors, fine.

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

But... When I create a new instance a model and add errors to this instance, the Class Exception appears as a global object. LOOK...

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]}

How can I solve this?

How do I make the Array of messages of class Exception is not GLOBAL?

  • I'm not sure how console.log(a.errors.messages) would display anything, as you are not altering the messages object present inside the errors object. Can you please show whole code? – Aravind Nov 15 '14 at 16:59
  • How do you construct `Validations` object? – dfsq Nov 15 '14 at 18:18
  • Scimonster answer is the right one, messages come from Exception.prototype and are shared among Exception instances. If you mutate prototype members on one instance it'll change this member on all instances. Maybe the following answer will help you in understanding instance specific, prototype members and shadowing: http://stackoverflow.com/a/16063711/1641941 – HMR Nov 16 '14 at 04:19

1 Answers1

1

The problem lies in your Exception class:

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 ?
    }
}

I assume that this.m and this.messages are supposed to be the same thing, so i'll treat it as if that's how it is.


Your messages object is tied to the Exception prototype. This means that it's shared across all instances. It's now a very simple fix: Just put it in the initiation.

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 ?
    }
}
Scimonster
  • 32,893
  • 9
  • 77
  • 89