【发布时间】:2017-11-26 04:45:41
【问题描述】:
在我的页面中,我有几个 img 标签如下:
<img class="img-fluid meeseks" src="img/meeseks_red.jpg" data-color="#ee5b61" />
在我创建的 js 文件中:
function Store(path,color){
this.path=path
this.color=color}
然后,开始编写代码,我写了这个:
img_path=[]
for (var i=0;i<img.length;i++){
img_path.push( new Store(img[i].getAttribute("src"),img[i].getAttribute("data-color")))
}
获取存储每张图片的src和颜色的对象数组。
现在,研究 IIFE,我写的这个似乎也有效:
(function store_inf(){
img_path=[]
for (var i=0;i<img.length;i++){
img_path.push( new Store(img[i].getAttribute("src"),img[i].getAttribute("data-color")))
}
return img_path
})()
在这种情况下哪种方式更好?我还注意到,如果我省略 return 事情正常工作(如果我记录 img_path 数组,我总是有一个对象数组)
所以 IIFE 在全局范围内返回一个永久的数组,即使在 IIFE 被调用之后? 谢谢
【问题讨论】:
-
没有。如果您使用变量而不声明它,它将成为全局范围的一部分。生命是无用的。
-
ok 正确的解决方案是: var img_path=[] for (var i=0;i
标签: javascript iife