我发现这个答案部分解决了我的问题,Invoke two functions with the same name
我的函数的工作方式是第一个“callBackLinks”运行,然后运行 //do new stuff here。
但是我有一个变量,它是我的“旧函数”的一部分,我需要将其添加到新函数中。
function callBackLinks(trgt){
//do stuff in here with trgt
}
var callBackLinks = function(oldFn){
return function(){
oldFn();
//do new stuff here
};
}(callBackLinks);
callBackLinks(trgt);
如何在第二个自启动函数中使用变量“trgt”?
最佳答案
只需将其传递到新返回的函数中即可:
function callBackLinks(target){
//do stuff in here with target
}
callBackLinks = function(oldFn) {
return function(target){
var links = oldFn(target);
// Do new stuff here with `target` and `links`
// including potentially, `return links`
};
}(callBackLinks);
callBackLinks(target);
如果您需要使用两个或三个以上的参数(或者如果 callBackLinks
可能会更改它接受的参数),您可以使用 Function.prototype.apply
调用oldFn:
return function(target) {
var links = oldFn.apply(this, arguments);
// Do things with `target` and `links` here
};
然后,如果 callBackLinks
更改为接受第二个 options
参数,您的调用者仍将获得预期的行为(但您不必处理您想要的参数)不关心)。
编辑
我添加了一个示例:
function callBackLinks(target){
//do stuff in here with target
target.innerHTML += "callBackLinks called\n"
}
callBackLinks = function(oldFn) {
return function(target){
var links = oldFn.apply(this, arguments);
// Do new stuff here with `target` and `links`
// including potentially, `return links`
target.innerHTML += "overridden function called\n"
return links;
};
}(callBackLinks);
callBackLinks(document.getElementById("screen"))
<pre id="screen">
This is the screen:
</pre>
关于javascript - 将变量传递给自启动函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33350738/