firebugの計測関数(console.time/console.timeEnd)を自動挿入

firebugの計測関数(console.time/console.timEnd)をつかってメソッドの実行時間の計測するときなどに、計測関数を挿入忘れと削除忘れしないために自動的に挿入するためのコードです
開発のときには、ブックマークレットで呼び出しておいて使うと便利かも(しません)。

フレームワーク部分(interceptor.js)

aop = {};
aop.interceptors = {};
aop.interceptors.TimeInterceptor = function(){};
aop.interceptors.TimeInterceptor.prototype.create = function(lambda) {
    var module = this.module;
    return function() {
        console.time(module);
        lambda.apply(this, arguments);
        console.timeEnd(module);
    };
};

aop.aspect = function(namespace, interceptor) {
    namespace = namespace.split('.');

    // 1. foo.barのオブジェクトを取得
    var obj = window;
    for (var i = 0, f = namespace.length; i < f;i++) {
        obj = obj[namespace[i]];
    };

    // 2. foo.barのオブジェクトを全捜査してフィールドがfunctionのときに、
    // 既存のfunctionをInterceptorでラップしている。
    namespace = namespace.join('.');
    for (i in obj) {
        var field = obj[i];
        interceptor.module = namespace + '.' + i;

        if (typeof(field) !== 'function') {
            continue;
        };

        // 既存のfunctionのプロパティなどをInterceptorでラップしたfunctionにコピーしている。
        var newField = obj[i] = interceptor.create(field);
        for (var j in field) {
            newField[j] = field[j];
        };
    };
};
動かすためのサンプル
foo = {};
foo.bar = {};
foo.bar.hoge = function() { alert('hoge'); };

// foo.barにTimeInterceptorを適用
aop.aspect('foo.bar', new aop.interceptors.TimeInterceptor());
foo.bar.hoge();

課題とか

  • prototypeに対応は未考慮