在解决这个问题方面,我有我只是在这里完成了一个完全可行的解决方案:
// 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);
}
}