我感兴趣的是有一种方法可以减少对以下构造函数上的injectMethod的调用次数:
function InjectScriptsAndExecute(url) {
this.url = url;
this.injectMethod = function() {
var inject = $.ajax({
url: this.url,
cache: true,
dataType: 'script'
});
return inject;
}
}
var pngFix = new InjectScriptsAndExecute("/Global/ICIS/Scripts/DD_belatedPNG_0.0.8a-min.js");
var pngList = new InjectScriptsAndExecute("/Global/ICIS/Scripts/DD_PNG_listing.js");
pngFix.injectMethod();
pngList.injectMethod();有没有一种方法可以将一个对象传递给包含任意多个URL引用的构造函数,而不必声明一个新变量并随后调用该方法?
发布于 2011-01-07 00:31:21
您可以让构造函数接收一个对象或数组,但您仍然只创建了一个实例。
一种解决方法是修改构造函数,以便您将其作为常规函数调用(没有new),并将其传递给urls数组。然后,它将迭代数组,进行递归调用,但使用new关键字,并用新实例覆盖每个url。
然后,它将返回原始的Array。
function InjectScriptsAndExecute(url) {
if (Object.prototype.toString.call(url).indexOf('Array') != -1) {
for (var i = 0, len = url.length; i < len; i++) {
url[i] = new InjectScriptsAndExecute(url[i]);
}
return url;
} else {
this.url = url;
this.injectMethod = function() {
var inject = $.ajax({
url: this.url,
cache: true,
dataType: 'script'
});
return inject;
}
}
}
var arr = InjectScriptsAndExecute(["/Global/ICIS/Scripts/DD_belatedPNG_0.0.8a-min.js",
"/Global/ICIS/Scripts/DD_PNG_listing.js"
]);
var len = arr.length;
while( len-- ) {
arr[len].injectMethod();
}为了安全起见,您可能真的希望进行一些额外的检查,以查看函数是否作为构造函数被调用。您可能希望根据接收到的是Array还是String,为每种方法提供适当的行为。
发布于 2011-01-07 00:29:58
你可以--但是你将进入一个有趣的领域:
function InjectScriptsAndExecute() {
this.urls = Array.prototype.slice.call(arguments, 0);
this.injectMethod = function() {
for (var i=0; i < this.urls.length; i++) {
$.ajax({
url: this.urls[i],
cache: true,
async: false, // Otherwise you cannot depend on the parse order
dataType: 'script'
});
}
}
// You can then use it in this way:
var all_scripts =
new InjectScriptsAndExecute("/Global/ICIS/Scripts/DD_belatedPNG_0.0.8a-min.js",
"/Global/ICIS/Scripts/DD_PNG_listing.js");
all_scripts.injectMethod();如果您使用任何频率执行此操作,您可能需要一个像Require.js或LAB.js这样的依赖项管理器。如果你正在寻找一个完整的框架,Dojo和YUI也提供了依赖管理。
https://stackoverflow.com/questions/4617055
复制相似问题