我有一个无法修改的函数:
function addToMe() { doStuff(); }
我可以添加这个功能吗? 显然这个语法是非常错误的,但这是一般的想法......
function addToMe() { addToMe() + doOtherStuff(); }
最佳答案
您可以存储对原始函数的引用,然后使用回调原始函数的函数覆盖它,并添加您想要的功能:
var originalFn = addToMe;
addToMe = function () {
originalFn(); // call the original function
// other stuff
};
你可以这样做,因为 JavaScript functions是first-class对象。
编辑:如果您的函数接收参数,则应使用 apply将它们传递给原始函数:
addToMe = function () {
originalFn.apply(this, arguments); // preserve the arguments
// other stuff
};
您还可以使用带有参数的自动执行函数表达式来存储原始函数的引用,我认为它更干净一点:
addToMe = (function (originalFn) {
return function () {
originalFn.apply(originalFn, arguments); // call the original function
// other stuff
};
})(addToMe); // pass the reference of the original function
关于javascript - 添加到 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1659219/