javascript - 将变量传递给自启动函数

标签 javascript jquery function

我发现这个答案部分解决了我的问题,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/

相关文章:

function - 为什么不支持高阶函数中的注释?

c# - 如何使用 MysqlConnector 调用 mysql 函数?

javascript - 如何使用cookie来检测用户是否已经提交了表单?

javascript - 在 JavaScript 中删除数组元素 - 删除与拼接

javascript - jQuery fadeOut() 只工作一次

javascript - 使用jquery动态添加表单元素到动态表单

javascript - 从外部文件调用外部 JS 函数

javascript - Google map javascript Api 无法在本地主机上运行

javascript - jquery发送获取和更改图像源

Python:如何并行运行两个函数