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());
// ###################################