简而言之,我想用较新的函数覆盖 JavaScript 函数,但在该较新的函数中我希望能够调用旧函数。例如:
function test()
{
alert('original');
}
// then some time later
function test()
{
alert('new function');
}
// call function
test();
在这种情况下,仅调用最后一个test()
。因此新功能
会收到警报。
但是有没有办法也调用第一个 test()
方法?那么两个 test()
函数都被调用了吗?
我需要这个的原因是因为 Web 应用程序生成一个 onSave()
方法。通过Ajax保存表单时会触发该函数。
我想在保存表单时做一些额外的事情,但我不能只更改原始的 onSave()
函数。这就是为什么我正在寻找一种方法来扩展它。
我该怎么做?
最佳答案
function test()
{
console.log('original');
}
var test = function (oldFn) {
// /\
// -------
// \/
return function () { // <- return a new function which will get stored in `test`
oldFn(); // use the passed `oldFn`
console.log('new function'); // the new code
};
}(test); // <- pass in the old function, we do this, to avoid reference problems
// call function
test();
关于javascript - 调用两个同名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16603985/