SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Jul 2006
    Posts
    35
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How do you convert a string into a variable/function reference?

    Suppose I pass a string as an argument to a function, but I want that string to represent a variable or a function (assume no scope issues).

    How can I accomplish this?

  2. #2
    SitePoint Enthusiast
    Join Date
    Jun 2008
    Location
    South Florida
    Posts
    50
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Can you post some code so we can see a little more clearer?

  3. #3
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    eval("blah") or window["blah"] for globals.

  4. #4
    SitePoint Evangelist vikrantkorde's Avatar
    Join Date
    Jun 2004
    Location
    Mumbai, India
    Posts
    541
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    eval("xyz(" + i + ")");

    assuming i = 10, this is equivalent to
    xyz(10);
    Vikrant Korde
    S Y S T I M E, Mhape,
    Mumbai, Maharashtra, India.

  5. #5
    SitePoint Enthusiast
    Join Date
    Jul 2006
    Posts
    35
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I knew of eval, will that also work for function names?

    Say I pass "Math.sin" to a function argument of myFunc.

    Would: eval(myFunc(Math.PI)); give me 0 as it should?

    Also, what about this situation:

    var a = 123;
    var b = 456;
    function testFunc(var1, var2) {

    }

    If I pass "a" or "b" as var1 or var2, how can I get them to point to the variables of the same name and not be strings? I could put everything in an object and handle it that way, but I'd rather not. I've also used a switch with a third variable:

    switch(var1) {
    case "a": value = 123;
    case "b": value = 456;
    }

    value being the extra variable.
    Is there a more efficient way to accomplish that?

    Thanks,
    Shane


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •