Image对象的关联数组的简写

use*_*753 2 javascript arrays object

我想在Javascript中创建一个关联数组,其中我将有一堆指向Image对象的字符串键.原因是我想要预先加载并动态控制大量图像,而不会用数百个全局变量污染全局空间.例如,要避免以下情况:

var img1, img2, img3, ... , img99; 
img1 = img2 = img3 = ... = img99 = new Image();
Run Code Online (Sandbox Code Playgroud)

相反,我只想通过一些可识别的字符串名称来调用图像,以使代码更易于阅读,并且_images在全局空间中只有一个变量.

起初,我试图使用an Array来执行此任务,但却发现没有用于指定Array带字符串键的实例化的语法.进一步的调查使我在这里,甚至可以说,Array用作关联阵列可能是有害的.

以前,我曾假定的Javascript阵列类似于LUA表,其中有一个索引部分(其大小被保持在length属性)和散列部分(字符串索引).显然,事实并非如此.相反,在指定"字符串键"时,它实际上只是指定对象属性的简写.

因此,我终于走上了这条道路:

var _images = {
    "button_mouseover": new Image(),
    "button_mouseout": new Image(),
    "button_mousedown": new Image(),
    "button_mouseup": new Image()       
}
Run Code Online (Sandbox Code Playgroud)

其中我创建了一个对象(其引用存储在其中_images),其中包含一系列属性,每个属性都存储对实例化Image对象的引用.

现在填充src所有图像的属性,至少可以说是相当冗长:

_images["button_mouseover"].src = "fsfs.gif";
_images["button_mouseout"].src = "gsgs.gif";
_images["button_mousedown"].src = "agag.gif";
_images["button_mouseup"].src = "ggg.gif";
Run Code Online (Sandbox Code Playgroud)

Image构造函数上找到非w3schools规范(默认类型)本身很难(有一个问题就是它的位置!).显然,构造只需要一个可选的widthheight,但没有源属性.

因此,很自然,我认为接下来的路线是的可能性延长Image,这样我也许可以缩短这件事有点构造函数:

var _images = {
    "button_mouseover": new Image("fsfs.gif"),
    "button_mouseout": new Image("gsgs.gif"),
    "button_mousedown": new Image("agag.gif"),
    "button_mouseup": new Image("ggg.gif")      
}
Run Code Online (Sandbox Code Playgroud)

这引出了我这个问题.似乎有这样的耻辱,它是可能的,但不太可能在所有浏览器中工作,并且扩展默认类型是禁忌.

这让我想到了我的问题:

  1. 延长Image真正构造不会在某些浏览器工作?
  2. 有没有其他Javascript对象符号来做这个我忽略了?

要么

我只是不得不列出所有属性,新的Image()调用,然后是一个单独的部分,再次列出所有的键和源?

要么

我应该只使用辅助功能,例如:

function Image2( src ) {
    var t = new Image();
    t.src = src;
    return t;   
}

var _images = {
    "button_mouseover": Image2("fsfs.gif"),
    "button_mouseout": Image2("gsgs.gif"),
    "button_mousedown": Image2("agag.gif"),
    "button_mouseup": Image2("ggg.gif")     
}
Run Code Online (Sandbox Code Playgroud)

Nie*_*sol 7

辅助功能可能是您最好的选择,因为它将所有重复代码分组到一个函数中.

我个人会这样做:

(function() {
    var img = function(src) {
        var t = new Image();
        t.src = src;
        return t;
    };
    window._images = {
        "over": img("fsfs.gif"),
        "out": img("gsgs.gif"),
        "down": img("agag.gif"),
        "up": img("ggg.gif")
    };
})();
Run Code Online (Sandbox Code Playgroud)

拥有较短的属性名称可以帮助保持代码合理的大小而不会丢失太多的可读性.