Every time the factory
function is called, it generates a new class instance.
Therefore, adding the add
method to the prototype of a class created by a specific call to the factory
function will not affect classes produced by other calls to the same function.
The provided demonstration illustrates how you can achieve the desired outcome.
function factory() {
class A {
add(num) {
return num + 1;
}
}
return A;
}
const MyClass = factory();
MyClass.prototype.add = function (num) {
return num + 2;
};
const b = new MyClass();
console.log(b.add(1));
If the factory
function is invoked again, it will yield a fresh class with an add
method that only adds 1.
The subsequent example demonstrates this behavior:
function factory() {
class A {
add(num) {
return num + 1;
}
}
return A;
}
const MyClassA = factory();
const MyClassB = factory();
// Override "add" method in MyClassA
MyClassA.prototype.add = function (num) {
return num + 2;
};
console.log(new MyClassA().add(1)); // 3
console.log(new MyClassB().add(1)); // 2 (MyClassB utilizes the default "add" method)
Consequently, each invocation of the factory
function necessitates the addition of the add
method to the prototype.
To prevent the repeated overwriting of the add
method in different calls to the factory
function, one solution is to create a separate function that:
- Invokes the
factory
function
- Modifies the
add
method
- Returns the updated class instance
This approach allows for reusable code that updates the add
method consistently.
The following code presents an example:
function factory() {
class A {
add(num) {
return num + 1;
}
}
return A;
}
function factoryWrapper() {
const MyClass = factory();
MyClass.prototype.add = function(num) {
return num + 2;
};
return MyClass;
}
const Class1 = factoryWrapper();
const Class2 = factoryWrapper();
console.log(new Class1().add(1));
console.log(new Class2().add(1));