0

I'm simply working on a namespace and class system in Javascript and I've been trying to get some getters/setter working.

In my code I pass an object to a function CreateClass. It reads a key from the object of the form propX where the name of the property is X.

At the end I try to call getX() but it returns Y's value of HELLO. The problem is originating in the lines 22 - 33. I think it may be that creating a new name variable it's overwriting X's name.

Is there a way to avoid this? Like being able to clone name so that it stays unique for getX

var global_ns = {}

function AddNamespace(ns, names) {
  var names_split = names.split('.');
  for (var i = 0; i < names_split.length; i++) {
    var name = names_split[i];
    if (!(name in ns)) {
      ns[name] = {}
    }
    ns = ns[name];
  }
}

function CreateClass(attributes) {
  var cls = function() {
    for (var key in attributes) {
      if (attributes.hasOwnProperty(key)) {
        if (key == 'ctor') {
          this.ctor = attributes[key];
        } else {
         // ###################################
          var found = key.match(/^prop(\w[\d\w_\?]*)$/);
          if (found) {
            var prop = attributes[key];
            var name = found[1];
            this[name] = prop.init_value;
            this['get' + name] = function() {
              return this[name];
            }
            this['set' + name] = function(value) {
              this[name] = value;
            }
          }
          // ###################################
        }
      }
    }
    if (this.ctor) {
      var ctor_values = new this.ctor();
      for (var key in ctor_values) {
        if (ctor_values.hasOwnProperty(key)) {
          this[key] = ctor_values[key];
        }
      }
    }
  }
  return cls;
}

AddNamespace(global_ns, "a.b.c");

// ###################################
var simple_class = CreateClass({
  ctor: function() {
    this.a = 123;
    this.b = "something";
  },
  propX: {
    init_value: 10
  },
  propY: {
    init_value: "HELLO"
  }
});

var cls = new simple_class();

console.log(cls.getX());
// ###################################
melpomene
  • 84,125
  • 8
  • 85
  • 148
PurityLake
  • 1,110
  • 10
  • 18
  • 1
    I'd rather see the code here – j08691 Mar 24 '17 at 14:21
  • 2
    "*a namespace and class system*" - don't, use ES6. – Bergi Mar 24 '17 at 14:32
  • To clarify the duplicate: it's about the `name` variable in your `CreateClass` function. Also, what Bergi says. – Just a student Mar 24 '17 at 14:33
  • I also subscribe Bergi words. In any case, if you just want to make this code work and use ES6 just replace var for let in yout for loop, and if you want to know why it works just read this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Scoping_rules_2 :) – MSánchez Mar 24 '17 at 14:59

0 Answers0