如何将字符串转换为对象?

时间:2012-04-08 23:50:48

标签: javascript

我预加载我的javascript文件顶部的两个不同图像。

var imgColor = new Image();
var imgLoadedColor = false;
imgColor.src = 'color/progress.png';

imgColor.onload = function(){
  imgLoadedColor = true;
}   

var imgBlackWhite = new Image();
var imgLoadedColor = false;
imgBlackWhite.src = 'blackWhite/progress.png';

imgBlackWhite.onload = function(){
  imgLoadedColor = true;
}   

this.options.type中的字符串为imgColorimgBlackWhite

当我尝试将参数this.options.type传递给函数时,我收到错误,因为this.options.type中的值是一个字符串,而不是一个对象。但是,如果我传递参数imgColor,它会加载彩色图像,如果我传递参数imgBlackWhite,则会加载黑白图像,因为imgColorimgBlackWhite是对象。 / p>

如何根据imgColor中字符串的值创建对象imgBlackWhitethis.options.type的引用?

2 个答案:

答案 0 :(得分:1)

为什么不使用if语句?

if (arg == "imgColor") return imgColor;
else return imgBlackWhite;

编辑:你也可以使用新的windowtypename来实例化一个对象(按照这个帖子:Instantiate a JavaScript Object Using a String to Define the Class Name)。所以,而不是上述:

return new window[arg]();

答案 1 :(得分:0)

传递参数:

this[this.options.type]
相关问题