添加到JavaScript函数 [英] Add to a javascript function
问题描述
我有一个我无法修改的函数:
function addToMe(){doStuff(); }
我可以添加到此功能吗?
function addToMe(){ addToMe()+ doOtherStuff(); }
您可以存储对原始函数的引用,然后用一个函数调用原始函数并添加你想要的功能:
var originalFn = addToMe ;
addToMe = function(){
originalFn(); //调用原始函数
//其他东西
};
您可以这样做,因为JavaScript functions 是头等舱。
$ b 编辑:如果您的函数接收参数,您应该使用 apply 将它们传递给原始函数:
addToMe = function(){
originalFn.apply(this,arguments); //保存参数
//其他东西
};
您也可以使用带参数的自动执行函数表达式来存储原始函数的引用,我认为它有点干净:
$ $ $ $ $ $ $ $ addToMe =(function(originalFn){
return function() {
originalFn.apply(originalFn,arguments); //调用原始函数
//其他东西
};
})(addToMe); //传递原始函数的引用
I have a function I can't modify:
function addToMe() { doStuff(); }
Can I add to this function? Obviously this syntax is terribly wrong but it's the general idea...
function addToMe() { addToMe() + doOtherStuff(); }
You could store a reference to the original function, and then override it, with a function that calls back the original one, and adds the functionality you desire:
var originalFn = addToMe;
addToMe = function () {
originalFn(); // call the original function
// other stuff
};
You can do this because JavaScript functions are first-class objects.
Edit: If your function receives arguments, you should use apply to pass them to the original function:
addToMe = function () {
originalFn.apply(this, arguments); // preserve the arguments
// other stuff
};
You could also use an auto-executing function expression with an argument to store the reference of the original function, I think it is a little bit cleaner:
addToMe = (function (originalFn) {
return function () {
originalFn.apply(originalFn, arguments); // call the original function
// other stuff
};
})(addToMe); // pass the reference of the original function
这篇关于添加到JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!