Jeff
Jeff

Reputation: 480

Easy way (with out eval) to turn a passed string into an object refereance in JS?

So let's say I have a in page function:

<img src="someImage.jpg" onclick="doSomething(this.id)" id="someVar" alt="blah" />

and I have a class set up:

function anObject(someProp)
{
this.someProp=someProp;
}
someVar=anObject("prop");

Where I have trouble is in the doSomething function:

function doSomething(theObject)
{
alert(theObject.someProp); //this is treated as "someVar".someProp as far as I can tell instead of someVar.someProp
}

Basically, I would like to be able to use that reference as an object reference instead of a string, is there an easy way to do this without eval?

Also is there some way to ensure the oppisite, that it is treated as a string instead of an object?

EDIT: I am attempting to reference the object with the same name as the image's ID NOT the image itself.

Upvotes: 1

Views: 148

Answers (3)

Martijn
Martijn

Reputation: 13622

I'd use a collection object:

// Create an object with a property 'someProp', and return it
// (No messing with 'this')
function createSomeObject(someProp) {
  return {
    someProp: someProp
  };
}

// Keep a collection of variables
var someVars = {};
someVars.someVar = createSomeObject('prop');
someVars.otherVar = createSomeObject('prop2');

So you can reference them like this:

<img src="someImage.jpg" onclick="doSomething(this)" id="someVar" alt="blah" />

And then you can get the original object like this:

function doSomething(imageElement) {
    var someVar = someVars[imageElement.id];
    alert(someVar.someProp); // this will return "prop"
}

Upvotes: 1

Victor
Victor

Reputation: 4721

Well you are passing a string (this.id) instead of an object to your function. Should be:

<img src="someImage.jpg" onclick="doSomething(this)" id="someVar" alt="blah" />

Upvotes: 1

Kris Ivanov
Kris Ivanov

Reputation: 10598

doSomething(this) 

drop the .id that will give you ref to the actual DOM element as an object

Upvotes: 2

Related Questions