To add a new method directly to the class declaration, you can do the following:
class BaseClass extends ParentBase {
foo() {functions["foo"](); }
}
If you need the method name to be dynamic, computed method names can be used like this:
class BaseClass extends ParentBase {
[window.location]() {functions["foo"](); }
}
If you want to dynamically inject a new method (such as conditionally or in a loop), write into BaseClass.prototype
:
BaseClass.prototype.foo = functions["foo"];
To create a non-enumerable property, use Object.defineProperty
like this:
Object.defineProperty(BaseClass.prototype, "foo", {
value: functions["foo"],
});
Below is a demonstration of adding methods to a class:
class ParentBase {
parentHello() {
console.log('parentHello')
}
}
function Base() {
class BaseClass extends ParentBase {
instanceMethod() { console.log("BaseClass.prototoype.test", this); };
static classMethod() { console.log("BaseClass.classMethod", this); };
}
BaseClass.classMethod2 = function() { console.log("BaseClass.classMethod2", this); };
BaseClass.prototype.instanceMethod2 = function() { console.log("BaseClass.prototype.instanceMethod2", this); };
Object.defineProperty(BaseClass.prototype, "instanceMethod3", { value() { console.log("BaseClass.prototype.instanceMethod3", this); } });
return BaseClass;
}
const Class = Base();
const instance = new Class();
Class.classMethod();
Class.classMethod2();
instance.instanceMethod();
instance.instanceMethod2();
instance.instanceMethod3();