Andrei Nemes
Andrei Nemes

Reputation: 3122

Function to create class

I am trying to create a robust way to define classes "on the fly", but I'm afraid of adding unnecessary overhead to the whole process.

Here is my creation code:

function Class(cons,proto) {
    var keys = Object.keys(cons);

    function _class() {
        var i = keys.length;
        while( i-- ) {
            this[ keys[i] ] = arguments[i] || cons[keys[i]];
        }
    }

    if(proto) {
        var f;
        for (f in proto) {
            _class.prototype[f] = proto[ f ];
        }
    }

    return _class
}

And here is how I want to use it

var car = Class({
                "name": "A car",
                "power": 900
            },
            {
                "honk": function() { alert("honk!") } 
            });


var bmw = new car("BMW", 500);
bmw.honk();     // -> honk!
console.log( bmw.name, bmw.power );     // -> BMW 500

var generic = new car();
generic.honk = function() { alert("custom honk") };
generic.honk();     // -> custom honk!

alert( bmw.honk === car.prototype.honk );   // -> true
alert( generic.honk === car.prototype.honk );       // -> false

console.log( generic.name, generic.power );     // -> A car 900

Am I doing anything unnecessary? Do you have any suggestions for improvement? Please post your opinion

Upvotes: 1

Views: 68

Answers (1)

Bergi
Bergi

Reputation: 665101

Am I doing anything unnecessary?

Not that I can see, but you'd need to show us an actual use case for this instead of a demo example :-)

Do you have any suggestions for improvement?

Looping over Object.keys(cons) and using the i for anything else but keys[i] is errorprone, as Object.keys does not guarantee any order. It could as well happen that bmw.power is "BMW" and bmw.name is 500.

Upvotes: 1

Related Questions