减少对JavaScript对象方法的调用次数 [英] Reducing number of calls to the methods of a JavaScript object

查看:127
本文介绍了减少对JavaScript对象方法的调用次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对减少以下构造函数上的injectMethod调用次数的方法感兴趣:

I was interested in a way to reduce the number of calls to the injectMethod on the below constructor function:

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引用的构造函数,而无需声明新变量并随后调用该方法?

Is there a way i can pass an object to the constructor function that contains as many URL references as i like without having to declare a new variable and subsequently call the method?

推荐答案

您可以让构造函数接收一个对象或数组,但是您仍然仅创建一个实例.

You could have the constructor receive an object or array, but you're still only creating one instance.

一种解决方法是修改构造函数,以便将其作为常规函数调用(不带new),并将其传递给url数组.然后,它将遍历数组,进行递归调用,但使用关键字 ,并用新实例覆盖每个url.

One way around it would be to modify the constructor so that you call it as a regular function (without new), and pass it an Array of the urls. Then it will iterate over the array, making a recursive call, but with the new keyword, and overwriting each url with the new instance.

然后它将返回原始数组.

Then it would return the original 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();
}

为了安全起见,您真的希望进行一些其他检查,以查看该函数是否作为构造函数被调用.而且,您希望每个对象都具有适当的行为,具体取决于它接收到的是数组还是字符串.

For safety, you would really want to have some additional checks to see if the function is being called as the constructor or not. And you'd want to have appropriate behavior for each depending on whether it received an Array or a String.

这篇关于减少对JavaScript对象方法的调用次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆