Javascript — Dynamically generating Accessor and Mutation methods

This is a neat trick I picked up the oth­er day, you can cre­ate a dynam­ic class which takes in a set of prop­er­ties in the con­struc­tor and dynam­i­cal­ly gen­er­ates Acces­sor and/or Muta­tion meth­ods (you just have to choose which lines to leave out):

function DynamicClass(properties) {
    // store class scope into a local variable
    var _this = this;

    for (var i in properties) {
        (function (i) {
            // create access method
            _this["get" + i] = function () {
                return properties[i];
            };

            // and mutation method, delete to make the class immutable
            _this["set" + i] = function (value) {
                properties[i] = value;
            }
        })(i);
    }
}

In your call­ing code, you can then cre­ate a new class like this, just define and pro­vide the val­ue for the prop­er­ties you want to add to the class in the con­struc­tor call:

var obj = new DynamicClass({
    Name: "Dusty",
    Breed: "Highland Terrier",
    Age: 2
});

If you had added the muta­tion as well as the acces­sor meth­ods, you’d be able to use them once the object has been cre­at­ed:

obj.setAge(3);
alert("Name: " + obj.getName() + ", Age: " + obj.getAge() + ", Breed:" + obj.getBreed());

Bet­ter still, if you’re using Visu­al Stu­dio by any chance, intel­lisense will be able to pick up the dynam­i­cal­ly gen­er­at­ed get/set meth­ods on your new dynam­ic class:

image