Javascript — Dynamically generating Accessor and Mutation methods

This is a neat trick I picked up the other day, you can cre­ate a dynamic class which takes in a set of prop­er­ties in the con­struc­tor and dynam­i­cally 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;

In your call­ing code, you can then cre­ate a new class like this, just define and pro­vide the value 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 created:

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

Bet­ter still, if you’re using Visual Stu­dio by any chance, intel­lisense will be able to pick up the dynam­i­cally gen­er­ated get/set meth­ods on your new dynamic class:


  • Tee­ber­ryu

    Inter­est­ing. But intel­lisense can’t han­dle more com­plex object like this
    Name: “Dusty”,
    Breed: “High­land Ter­rier”,
    Age: 2,
    Com­plexOb­ject: {prop1 : 1,prop2 : “2”,prop3 : new Date()}
    And it can’t detect types for dynam­i­cally gen­er­ated accessors(obj[’Name’].contructor == String).