javascript - Create ES6 class from a function -


i'm trying explore using es6 classes instead of how currently, using function.prototype means. our api looks like:

var myclass = createclass('myclass', {     test : function() {} }); 

we iterate through object , apply properties onto function return, prettier way it's more inline other programming languages of sorts:

function myclass() {}  myclass.prototype.test = function() {}; 

we cache class onto object name key , function value use throughout our application. class name can namespaced can have my.cls , split period , cache onto manager can retrieved via window.my.cls.

looking es6 classes, don't see how can keep createclass function. love like:

function createclass(name, config) {     return class name config; } 

i didn't expect work , doesn't.

two issues have here:

  1. how can create class using variable class name?
  2. how can create class , assign properties via config object argument?

not sure possible. don't plan on keeping createclass, hope keep , upgrade our legacy "classes". i'd start using es6 classes not break whole app long it'll take upgrade.

the upgrade route refactor property hashes proper classes. can start work , keep using hash-based classes in meantime, lighten requirement @ once.

if have limited number of "class" name:config pairs -- should maintainability reasons -- can replace createclass implementation does:

class foo { ... } class bar { ... }  let classes = {'foo': foo, 'bar': bar}; function createclass(name, config) {   if (classes[name]) {     return classes[name];   }   // old impl } 

this ignore config if "real" implementation exists, keep using legacy behavior if haven't replaced class. if is, can implement createclass more like:

function createclass(name, config) {   if (classes[name]) {     return new classes[name](config);   }   // old impl } 

and pass config arguments class ctor. in case, may want filter out function properties (methods) first, class implements them already. like:

function createclass(name, config) {   if (classes[name]) {     let fields = object.keys(config).filter(key => {       return typeof config[key] !== 'function';     }).map(key => config[key]);      return new classes[name](fields);   }   // old impl } 

Comments

Popular posts from this blog

IF statement in MySQL trigger -

c++ - What does MSC in "// appease MSC" comments mean? -

javascript - Blogger related post gadget image Resize s72-c [ Need Expert Help ] -