在解决问题方面,我有一个完全可行的解决方案,我刚刚在这里完成:
// synchronous dynamic script loading.
// takes an array of js url's to be loaded in that specific order.
// assembles an array of functions that are referenced more directly rather than
// using only nested closures. I couldn't get it going with the closures and gave up on it.
function js_load(resources, cb_done) {
var cb_list = []; // this is not space optimal but nobody gives a damn
array_each(resources, function(r, i) {
cb_list[i] = function() {
var x = document.body.appendChild(document.createElement('script'));
x.src = r;
console.log("loading "+r);
x.onload = function() {
console.log("js_load: loaded "+r);
if (i === resources.length-1) {
cb_done();
} else {
cb_list[i+1]();
}
};
};
});
cb_list[0]();
}
我对此非常满意,因为它可以满足我现在的需求,并且可能比我的第一种方法(如果它成功的话)更容易调试。
但我无法克服的是为什么我永远无法让它工作。
它看起来像这样。
function js_load(resources, cb_done) {
var cur_cont = cb_done;
// So this is an iterative approach that makes a nested "function stack" where
// the inner functions are hidden inside the closures.
array_each_reverse(resources, function(r) {
// the stack of callbacks must be assembled in reverse order
var tmp_f = function() {
var x = document.body.appendChild(document.createElement('script'));
x.src = r;
console.log("loading "+r);
x.onload = function() { console.log("js_load: loaded "+r); cur_cont(); }; // TODO: get rid of this function creation once we know it works right
};
cur_cont = tmp_f; // Trying here to not make the function recursive. We're generating a closure with it inside. Doesn't seem to have worked :(
});
cur_cont();
}
它一直试图在无限循环中调用自己,以及其他奇怪的事情,并且在调试过程中很难识别函数是哪个函数以及函数包含什么。
我没有深入研究代码,但似乎jQuery.queue
也实现了与我的工作类似的机制(使用数组来跟踪延续队列),而不是仅使用闭包。
我的问题是:是否有可能构建一个可以将函数作为参数的 Javascript 函数,并通过构建包含它自己创建的函数的闭包来使用其他函数列表来增强它?
这真的很难描述。但我敢肯定,有人有一个适当的理论支持的数学术语。
PS 上面代码引用的就是这些例程
// iterates through array (which as you know is a hash), via a for loop over integers
// f receives args (value, index)
function array_each(arr, f) {
var l = arr.length; // will die if you modify the array in the loop function. BEWARE
for (var i=0; i<l; ++i) {
f(arr[i], i);
}
}
function array_each_reverse(arr, f) {
var l = arr.length; // will die if you modify the array in the loop function. BEWARE
for (var i=l-1; i>=0; --i) {
f(arr[i], i);
}
}