Javascript function hooks

后端 未结 7 1002
孤街浪徒
孤街浪徒 2020-12-24 15:17

EDIT: OK, I believe the following solutions are valid:

  1. Use the jQuery AOP plugin. It basically wraps the old function together with the hook into a function

7条回答
  •  爱一瞬间的悲伤
    2020-12-24 15:50

    This answer is not definitive, but rather demonstrative of a different technique than those offered thus far. This leverages the fact that a function in Javascript is a first-class object, and as such, a) you can pass it as a value to another function and b) you can add properties to it. Combine these traits with function's built-in "call" (or "apply") methods, and you have yourself a start toward a solution.

    var function_itself = function() {
        alert('in function itself');
    }
    function_itself.PRE_PROCESS = function() {
        alert('in pre_process');
    }
    function_itself.POST_PROCESS = function() {
        alert('in post_process');
    }
    
    var function_processor = function(func) {
        if (func.PRE_PROCESS) {
            func.PRE_PROCESS.call();
        }
        func.call();
        if (func.POST_PROCESS) {
            func.POST_PROCESS.call();
        }        
    }
    

提交回复
热议问题