-1

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.

Community
  • 1
  • 1
Charlie
  • 11,380
  • 19
  • 83
  • 138
  • Really haven't given enough information. Obviously you have more than one instance of "clock", and if not, why not just repeat the call with `clock.once()`? Why not have `once` accept the id argument? – Travis J Dec 24 '12 at 06:27
  • Why the downvote? I didn't realize not knowing something was considered bad. – Charlie Dec 24 '12 at 06:29
  • @Charlie: I think you were downvoted for how your question is formulated (it should provide more information), not for what you are asking. – Ortiga Dec 24 '12 at 06:31
  • @Andre Honestly I thought it was formatted fine. That's what my code looks like. There is only one instance of `clock`, but when a person clicks a link that has a different `href` attribute, it needs to run the `once()` function within the `id` object (that is the same as the `href` attr clicked, they are always the same). – Charlie Dec 24 '12 at 06:33

1 Answers1

1

[id].once is 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:

var clocks = [];
clocks.push(new clock());
clocks.push(new clock());

Then, you could index into that particular array like this assuming id was a valid index into that array:

clocks[id]

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:

parseInt(id, 10)
+id
jfriend00
  • 683,504
  • 96
  • 985
  • 979