You could directly declare a new method in the class declaration:
class BaseClass extends ParentBase {
foo() {functions["foo"](); }
}
If the method name should be dynamic, you can also use computed method names:
class BaseClass extends ParentBase {
[window.location]() {functions["foo"](); }
}
If you really want to "dynamically inject" a new method (e.g. conditionally, in a loop, or some other strange construct), you'd have to write into BaseClass.prototype
, which is the object BaseClass instances will inherit from:
BaseClass.prototype.foo = functions["foo"];
This will however be an enumerable property, to create a non enumerable one, use Object.defineProperty
:
Object.defineProperty(BaseClass.prototype, "foo", {
value: functions["foo"],
/* enumerable: false,
writable: false */
});
Here is a small showcase:
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();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…