Search code examples
javascriptwrapperobject-properties

How to access the current element property name of the called function


For logging purpose, I've created a wrapper function for an element functions properties. The wrapper function is above:

functionsWrapper: function () {
    for (i = 0, args = new Array(arguments.length); i < arguments.length; i++) {
        args[i] = arguments[i];
    }

    console.log('call for ' + arguments.callee.name + ' with params ' + argumantsLog(args));

    return this['original' + arguments.callee.name].apply(this, args);
}

And then I'm using this code to wrap the element function:

logFunctionsCalls: function (element) {
    if (!element)
        return;

    if (element.children && element.children.length)
        for (var i = 0; i < element.children.length; i++)
            logFunctionsCalls(element.children[i]);

    if (!element.functionsLogged) {
        element.functionsLogged = true;

        for (var property in element) {
            if (typeof element[property] != 'function')
                continue;

            element['original' + property] = element[property];
            element[property] = functionsWrapper;
        }
    }
}

My problem is that the arguments.callee contains the functionsWrapper code without the property name of the called function.


Solution

  • You cannot use the same functionWrapper everywhere - there's no way to find out as which property it was called. Instead, created different wrappers and keep the original in closure.

    for (var p in element) (function(property) {
        if (typeof element[property] != 'function')
            return;
    
        var original = element[property];
        element[property] = function wrapped() {
            console.log('call for ' + property + ' with params ' + Array.prototype.join.call(arguments));
            return original.apply(this, arguments);
        };
    }(p));