Possible Duplicate:
How to convert a string value to a variable in javascript?
In Javascript, I have an object that looks like this:
clock = function(){
this.load = function(){
alert("once");
}
this.once = function(){
alert("load");
}
}
var clock = new clock();
On the page load, I call the load() function within the clock object like so
clock.load();
When the user clicks a link, however, I need to be able to run clock.once(). Calling it like this is fine, but does not fit the dynamic needs of what I’m doing.
Let’s say I need to call clock.once() when the user clicks an <a> tag:
$("a").click(function(){
var id = $(this).attr("href").match(/[a-zA-Z]+/g);
[id].once();
}
I figured that would work, where the object that the once() function is being called from is grabbed from the string id.
When running this, however, I get the following error:
Uncaught TypeError: Object clock has no method ‘once’
Manually calling once() by using clock.once() works fine.
[id].onceis not not going to work because you aren’t referencing a particular array that you’ve created that contains clock objects. You would need a particular array where you had stored multiple instances of clock objects (if you had constructed the proper array).If you had previous create an array of clock objects:
Then, you could index into that particular array like this assuming id was a valid index into that array:
If you’re really just asking how to convert a string to a number, you can do that several ways. Here are two common ways: