Creating dynamic classes in javascript ES6

I have often wondered whether or not it is possible to dynamically create classes on the fly in javascript. Of course, using prototype inheritance, it is possible to do this simply by adding prototype methods on an object. But what if the class you are creating at runtime doesn’t actually know what methods it has to implement until an external source provides them? Further, in today’s day and age using ES 6 or 7, with babel, how can these classes be dynamically created on the fly from external implementations?

As it turns out, it is actually quite easy. Here is a code example:

let mymethod = 'myMethod'

class myClass {
  constructor() {
    console.log('class constructed')
  }

  [mymethod] (){
    console.log('hi')
  }
}

var my = new myClass()
my.myMethod()

This is great. It is a way of creating methods in the class without knowing the name of the method up front, but rather from a variable. But, this still is fairly limited, and why bother? If the implementation of the method is known in the file (via require/import or as a function in the javascript file), but what if the actual implementation of the method is stored elsewhere?  Now this is a challenge. One way is to add them on the prototype chain. This can be done as so:

var methods = {
  'increment': function() { this.value++; },
  'display' : function() { console.log(this.value); }
};

function addMethods(object, methods) {
  for (var name in methods) {
    object[name] = methods[name];
  }
};

var obj = { value: 3 };
addMethods(obj, methods);
obj.display();  // "3"
obj.increment();
obj.display();  // "4"

Another way is to add the events after the fact to the prototype chain, like this:

var obj = {value: 3 };
obj.prototype.mynewmethod = function method mynewmethod(myparam) {
//Dosomething, return something
}

But this is based on ES5 Javascript, not ES6.  While ES6 is merely “syntactic sugar” that transpiles to ES5 (using babel, tranceur, etc), it is still valid code. what it does is construct an object with functions in it (with dynamic class names) be mapped to an object’s prototype chain. This is a good way to add functions to an existing object.

But what if you don’t know the method’s implementation at run time (eg: download a method or function from somewhere else? This is where things get hairy. Because you don’t know the “source” of the method implementation, you have to trust that this source is trusted. Security issues come largely into play here. Javascript is a great language, especially with the ES6 “sugar”. But if you don’t understand the prototype chain, it is a bit of a double edge sword.