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 = [];
        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")




Please Do Not Reprint This Article

This article is copyrighted. Please do not reproduce or distribute this article in whole or part, in any form. Links to this article are welcome

Other Related Articles