mardi 9 février 2016

OOP Javascript using constructor as an object for static methods

I am always looking for new patterns to make code perform better and increase its readability.

I am using a method such as this to set the prototypes of a class before init:

// Definition 

function SomeClass(){}

SomeClass.set = function(methName, fn){
    SomeClass.prototype[methName] = fn;
};

// Add a new method prior to initialization
SomeClass.set('doSomethingUnique', function(a, b){ return a / b * a - b });

// Instantiation
var test = new SomeClass();
test.doSomethingUnique(4, 5);

This way I am able to use a "self contained" setter in order to avoid typing the typical SomeClass.prototype.doSomethingUnique = function(){...}. I am also allowed to use static methods without instantiating the class, which I feel added much more freedom to javascript classes (and allows just the type of behavior demonstrated above.

I don't see any real negatives to doing this, and as I consider this a code improvement due to it making my end result more modular and readable - it makes me wonder why I don't see this often in common O/S code. Can anyone else see any reason not to use this style/technique for purposes such as the the one explained above?

Thanks SO!

Aucun commentaire:

Enregistrer un commentaire