user784637
user784637

Reputation: 16162

How to convert a string to an object?

I preload load two different images at the top of my javascript file.

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.

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.

How do I create a reference to the objects imgColor and imgBlackWhite from the value of the string in this.options.type?

Upvotes: 0

Views: 122

Answers (2)

Paul
Paul

Reputation: 141927

Pass the argument:

this[this.options.type]

Upvotes: 0

McGarnagle
McGarnagle

Reputation: 102793

Why not just use an if statement?

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). So, instead of the above:

return new window[arg]();

Upvotes: 1

Related Questions