ES6 Class Extensions

Using standard es5 I have this method that allows me to add methods to the prototype chain of my library (this allows me to expand the main library, as well as any components that are attached to the library):

 library.extend = function(extendId, extendObj) {
        //if it an extension of the core library object...
        if(extendId === 'library') {
            library.prototype[extendObj.name] = extendObj.func;
        } else {
            library.component[extendId].prototype[extendObj.name] = extendObj;
        }
 }; 

Using:

 /* create some new class */
 var somecomponent = function() {}
 somecomponent.protoype.somemethod = function() {}

/* extend the base libraries prototype chain with the new class*/
library.extend('library', somecomponent)

In es6 classes, we also have prototypes, but they are masked by the class syntax, and you must add methods to the class using the method extends.

Because of this, I'm not sure how I can programmatically add methods to es6 classes using a method similar to the one I have above.

+4
source share
2 answers

es6 , , extends.

, "". , , - class .prototype. , extends, , , . , extends , , .

, ES6, , , .

, . , mixins .

+2

, .

ES5 , function, (.. ) :

function f() {}
f();     // Function call
new f(); // Constructor instantiation

ES6 , :

var f = () => {}; // Arrow function
f();              // Function call
new f();          // Error: f is not a constructor

class f {};       // Class
f();              // Error: Cannot call a class as a function
new f();          // Constructor instantiation

ES6 - [[Construct]] prototype. ES5.

,

class somecomponent { /* create some new class */
  somemethod() {}
}

/* extend the base libraries prototype chain with the new class*/
library.extend('library', somecomponent)

library.extend .

+2

Source: https://habr.com/ru/post/1616190/


All Articles