0

问题是,当我使用 test.call() 时,它会调用原型的调用实现,但是当我使用 test() 时,它不会调用 call()。我希望能够使用测试来触发prototype.call()。下面的代码:

            Function.prototype.call = function () {
            //do something...
            return this(); // call original method
        }

        function test() {
            alert("test");
        }

 test.call(); //calls prototype.call()
    test(); //doesnt call prototype.call()
4

2 回答 2

2

你为什么希望test()调用Function.prototype.call?它们是不同的功能。

.call()每次调用函数时都不会调用您要覆盖的本机方法。只有在调用它时才会调用它。

调用.call()确实调用test(),因为这是它的设计目的。它期望一个函数作为其上下文(this值),并调用该函数。但这并不意味着.call()与任何其他函数调用有任何关系。

于 2012-05-10T13:34:45.720 回答
1

这是我刚刚提出的一个解决方案(感谢悬崖金融指出了代码中的一个关键错误并进行了纠正)。它按调用顺序记录在某个点之后调用的所有非标准函数。

// array of all called functions
var calledFunctions = [];

// custom func object that has name of function and 
// and the actual function on it.

function func(_func, name) {
    return function() {
        calledFunctions.push(name)
        return _func.apply(this, arguments);
    };
}

test = function() {
    alert("hi");
}

otherTest = function() {
    alert("hello");
}

// put this bit somewhere after you've defined all your functions
// but *before* you've called any of them as all functions called
// after this point are logged. It logs all non-standard functions
// in the order that they are called.
for (prop in window) {
    if (window.hasOwnProperty(prop) && typeof window[prop] === 'function' && window[prop].toString().indexOf('[native code]') < 0) {
        window[prop] = func(window[prop], prop);
    }
}

otherTest();
test();
otherTest();

console.log(calledFunctions);​

工作演示可以在这里找到。

于 2012-05-10T14:27:29.517 回答