Blog

How to Create Dynamic Class in JavaScript

Here is a cool way to dynamially create a class in JavaScript:

function createDynamicClass(name, properties) {
    var obj = window[name] = function() {
        var self = this,
            args = [].slice.call(arguments);
        args.forEach(function(arg, idx) {
            self[properties[idx]] = arg;
        });
    };
    properties.forEach(function(prop) {
        obj.prototype[prop] = null;
    });
}

Example Usage


// define properties a "Hotel" class should have

var props = ['name', 'rooms', 'booked'];

// create a "Hotel" class

createDynamicClass("Hotel", props);

// create 3 "Hotel" with some properties missing to prove prototype

var hotels = [
    new Hotel("Hilton", 1000, 500),
    new Hotel("Best Western", 100),
    new Hotel("Motel 6")
];

Example

https://jsfiddle.net/1ndo2w2p/