简体   繁体   中英

Javascript OOP inherits create GLOBAL object

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM