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?

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

  1. Contain the "super" object instead of inheriting from it.
  2. 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.

Licenciado bajo: CC-BY-SA con atribución
scroll top