向所有函数添加一行代码

向所有函数添加一行代码

问题描述:

所以我在JS工作很多,我正在做很多事情(尽量保持模块化)。 Current我在每个函数的结尾调用 Event.fire('eventName')。我正在寻找一个方法在我的对象/类中有任何函数自动调用 Event.fire([function name])在所有函数的结尾

So I am working in JS a lot, and I am working a lot with events (try to stay as modular as possible). Current I am calling Event.fire('eventName') at the end of every function. I am looking for a way to have ANY function in my object/class automatically call an Event.fire([function name]) at the end of all functions

示例:

function MyClass(){
   this.on('someFunc', this.funcTwo);
   this.someFunc();
}
MyClass.prototype.on = function( event ){
   // the event stuff //
}
MyClass.prototype.someFunc = function(){
   console.log('someFunc');
}
MyClass.prototype.funcTwo = function(){
   console.log('funcTwo');
}


,动态修改你的函数:

You could try something like this, dynamically modifying your functions:

var obj = MyClass.prototype;
for (var prop in obj)
    if (typeof obj[prop] == "function") // maybe also prop != "on" and similar
        (function(name, old) {
            obj[prop] = function() {
                var res = old.apply(this, arguments);
                Event.fire(name);
                return res;
            };
        })(prop, obj[prop]);