将变量传递给自启动函数

时间:2015-10-26 16:23:59

标签: javascript jquery function

我发现这个答案部分解决了我的问题,Invoke two functions with the same name

我的功能与第一个" callBackLinks"运行然后运行//在这里做新的东西。

但我有一个变量,它将成为我的旧功能的一部分"我需要添加到新的。

function callBackLinks(trgt){

     //do stuff in here with trgt

}

var callBackLinks = function(oldFn){

    return function(){
        oldFn();

        //do new stuff here
    };
}(callBackLinks);



 callBackLinks(trgt);

如何使用变量" trgt"在第二个自我启动功能?

1 个答案:

答案 0 :(得分:3)

只需在新返回的函数中传递它:

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>
&#13;
&#13;
&#13;