如何访问被调用函数的当前元素属性名

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

本文关键字:元素 属性 函数 调用 何访问 访问      更新时间:2023-09-26

为了记录日志,我为元素函数的属性创建了一个包装器函数。包装器函数在上面:

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);
}

然后我用下面的代码来包装元素函数:

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;
        }
    }
}

我的问题是,arguments.callee包含functionsWrapper代码没有调用函数的属性名。

你不能在任何地方使用相同的functionWrapper -没有办法找出它被称为哪个属性。相反,创建不同的包装器,并保持原始的闭包。

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));