Técnica de encadenamiento genérico para el método sobrecargado
https://softwareengineering.stackexchange.com/questions/204557
-
29-09-2020 - |
Pregunta
Una operación común en JavaScript es reemplazar un método de objeto con uno nuevo mientras aún llama al método original.Esto se hace a menudo así:
var originalMethod = obj.method;
obj.method = function(arg) {
// call original method
originalMethod.call(this, arg);
// do my stuff new stuff
}
Me gustaría crear una función de utilidad para un método de objeto específico que maneja la parte de encadenamiento para que el usuario no tenga que preocuparse por ello.Una opción es usar el diseño anterior, en el que cada función agregada se envuelve en una nueva función que llama al anterior.Otra opción es crear una matriz de funciones y hacer que el método del objeto simplemente le duele sobre la matriz, llame a cada función a su vez.
function addXyzMethod1(fn) {
if (obj.method) {
var previousMethod = obj.method;
obj.method = function(value) {
value = previousMethod.call(this, value);
return fn.call(this, value);
};
} else {
obj.method = fn;
}
}
function addXyzMethod2(fn) {
if (obj._methodList) {
obj._methodList.push(fn);
} else if (obj.method) {
obj._methodList = [obj.method, fn];
obj.method = function(value) {
for (var i = 0, n = obj._methodList.length; i < n; i++) {
value = obj._methodList[i].call(this, value);
}
return value;
};
} else {
obj.method = fn;
}
}
En este punto, no puedo decidir qué método usarlo, ya que siento que las compensaciones de cada una son incluso.Entonces, mi pregunta aquí es: ¿cuál de estos métodos es mejor (más natural, o aceptado, o más rápido) o hay otro método que mejora en ambos?
Solución
Esta pregunta es bastante similar, o al menos se reduce a una pregunta similar aquí: https://stackoverflow.com/questions/660337 < / a>
Otros consejos
What you are trying to do is a JavaScript version of call super, which is described as a code smell by Martin Fowler.
I would suggest instead that you either
- Contain the "super" object instead of inheriting from it.
Use template method, such as below
templateMethod = function () { baseMethod(); if (overrideMethod) { overrideMethod(); } };
Other objects would call templateMethod. The overrideMethod is where child objects would have their code.