0

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?

user784637
  • 15,392
  • 32
  • 93
  • 156

2 Answers2

1

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]();
Community
  • 1
  • 1
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
0

Pass the argument:

this[this.options.type]
Paul
  • 139,544
  • 27
  • 275
  • 264