JavaScript调用函数的函数阵列具有相同的上下文



我正在尝试创建一个回调功能,或者至少是我的名字。主要目的是从具有相同上下文的数组调用功能,并能够从当前执行函数中调用数组中的下一个函数。

这是我想到的代码:

function callCallbackChain(context, callbackChain, params) {
    callbackChain.push(function () {
        return true;
    });
    for (var i = 0, len = callbackChain.length - 1; i < len; i++) {
        var cb   = callbackChain[i];
        var next = callbackChain[i + 1];
        if (typeof cb === "function") {
            cb.apply(context, [next].concat(params));
        }
    }
}
var callbackChain = [
    function (next, foo) {
        console.log('1 function call', arguments);
        this.innerHTML = this.innerHTML + "function called + context:" + foo + "<br>";
        next()
    },
    function (next, foo) {
        console.log('2 function call', arguments);
        this.innerHTML = this.innerHTML + "function called + context:" + foo + "<br>";
        next()
    },
    function (next, foo) {
        console.log('3 function call', arguments);
        this.innerHTML = this.innerHTML + "function called + context:" + foo + "<br>";
        next()
    }
];
var d = document.querySelector("#conent");
callCallbackChain(d, callbackChain, ["param from the main function"]);
<div id="conent">
  Initial Content
  
</div>

我似乎无法正确设置next功能。这是一个中间件。

您的 next函数实际上不可能是链中的下一个功能。

它的目的是运行下一个功能。

function run(context, chain, params) {
  var inner_run = (context, chain, params, index) => {
    next = () => inner_run(context, chain, params, index + 1);
    if (index < chain.length) chain[index].apply(context, [next].concat(params));
  };
  inner_run(context, chain, params, 0);
}
var chain = [
  function (next, foo) {
    this.first = true
    console.log('first', arguments);
    next()
  },
  function (next, foo) {
    this.second = true
    console.log('second', arguments);
    // not calling next()
  },
  function (next, foo) {
    this.third = true
    console.log('third', arguments);
    next()
  }
];
var context = {};
run(context, chain, ["param"]);
console.log('context', context);

您需要飞行绑定它:

var nextelem=0;
function next(params...){
 temp=nextelem;
 nextelem++;
 callbackChain[temp].bind(context)(next,...params);
}
//pass it
nextelem=1;
callbackChain[0].bind(context)(next);

最新更新