我正在创建一个插件,我想在其中加载几个脚本,并为每个脚本运行函数
plugin
。
我创建了一个
set of tests/examples
(代码如下)。
问题:
-
阿贾克斯照常传球
data, textStatus, jqxhr
参数集。但显然也创造了一个范围
插件
功能可用。在文档中找不到有关此的任何信息。请提供更多详细信息/解释!
-
到底是什么
this
这似乎在范围之内?
-
第三个示例中,我通过映射脚本名称列表来运行get script,其效果与预期一样。
-
建立延迟列表,然后运行
when
行为怪异。我没有得到函数已运行的指示(没有输出),当我消除延迟时,它似乎总是首先完成(“完成”比其他所有内容都要提前打印)。功能是否正在运行?我尝试添加
alert
当我使用
什么时候
。
指数js公司
var script_names = ["one.js", "two.js", "three.js"];
function as_callback(script_name)
{
console.log("plugin function run as callback");
console.log(`$.getScript(${script_name}, (data, textStatus, jqxhr) => plugin());`);
$.getScript(script_name, (data, textStatus, jqxhr) => plugin());
console.log();
}
function from_this(script_name)
{
console.log("plugin function referred to from 'this'");
console.log(`$.getScript(${script_name}, (data, textStatus, jqxhr) => this.plugin());`);
$.getScript(script_name, (data, textStatus, jqxhr) => this.plugin());
console.log();
}
function with_map(script_names)
{
console.log("with map");
console.log("string_names: " + JSON.stringify(script_names));
console.log(`
script_names.map((x) =>
{
$.getScript(x, (data, textStatus, jqxhr) => plugin())
});
`);
script_names.map((x) =>
{
$.getScript(x, (data, textStatus, jqxhr) => plugin())
});
console.log();
}
function with_push_and_when(script_names)
{
console.log("build array of deferred and run with when");
console.log(`
var plugs = [];
script_names.map(x => $.getScript(x, (data, textStatus, jqxhr) => plugs.push(plugin)));
$.when(plugs).done(console.log("done"));
`);
var plugs = [];
script_names.map(x => $.getScript(x, (data, textStatus, jqxhr) => plugs.push(plugin)));
$.when(plugs).done(console.log("done"));
console.log();
}
as_callback('one.js');
setTimeout("from_this('two.js')", 2000);
setTimeout("with_map(script_names)", 4000);
setTimeout("with_push_and_when(script_names)", 6000);
var plugs = [];
script_names.map(x => $.getScript(x, (data, textStatus, jqxhr) => plugs.push(plugin)));
setTimeout("console.log('run when in global scope');$.when(plugs).done(console.log('done'))", 8000);
一js公司
var plugin = function()
{
console.log("one.js\n\n");
// alert("one");
return "one";
}
二js公司
var plugin = function()
{
console.log("two.js\n\n");
return "two";
}
三js公司
var plugin = function()
{
console.log("three.js\n\n");
return "three";
}
输出
plugin function run as callback
$.getScript(one.js, (data, textStatus, jqxhr) => plugin());
one.js
plugin function referred to from 'this'
$.getScript(two.js, (data, textStatus, jqxhr) => this.plugin());
two.js
with map
string_names: ["one.js","two.js","three.js"]
script_names.map((x) =>
{
$.getScript(x, (data, textStatus, jqxhr) => plugin())
});
two.js
three.js
one.js
build array of deferred and run with when
var plugs = [];
script_names.map(x => $.getScript(x, (data, textStatus, jqxhr) => plugs.push(plugin)));
$.when(plugs).done(console.log("done"));
done
run when in global scope
done
注:
我将已接受的答案添加到
回复:。信息技术
。