简体   繁体   English

如何将字符串转换为 object?

[英]How to convert a string to an object?

I preload load two different images at the top of my javascript file.我在 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;
}   

The string in this.options.type is either imgColor or imgBlackWhite . imgBlackWhite中的字符串是this.options.typeimgColor

When I try to pass the argument this.options.type to a function, I get an error because the value in this.options.type is a string, not an object. However if I pass the argument imgColor it loads the colored image and if I pass the argument imgBlackWhite it loads the black and white image because imgColor and imgBlackWhite are objects.当我尝试将参数this.options.type传递给 function 时,出现错误,因为this.options.type中的值是一个字符串,而不是 object。但是,如果我传递参数imgColor ,它会加载彩色图像并如果我传递参数imgBlackWhite ,它会加载黑白图像,因为imgColorimgBlackWhite是对象。

How do I create a reference to the objects imgColor and imgBlackWhite from the value of the string in this.options.type ?如何从 this.options.type 中的字符串值创建对对象imgColorimgBlackWhitethis.options.type

Why not just use an if statement?为什么不直接使用 if 语句呢?

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

EDIT: you can also use new windowtypename to instantiate an object (per this thread: Instantiate a JavaScript Object Using a String to Define the Class Name ).编辑:您还可以使用新的 windowtypename 实例化 object(根据此线程: Instantiate a JavaScript Object Using a String to Define the Class Name )。 So, instead of the above:所以,而不是上面的:

return new window[arg]();

Pass the argument:传递参数:

this[this.options.type]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM