SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Evangelist comfixit's Avatar
    Join Date
    Dec 2004
    Location
    Pasadena
    Posts
    537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Exposing a local Javascript function globaly

    Alright I got a really weird application.

    I have a couple of functions that I have converted into strings. I then run those through an Eval statement, and they work just as if I had written the functions directly.

    Now that the initial tests are successfull I want to abstract my code a bit and run the eval statement inside a function.

    The function as it stands now:
    Code:
    	function loadFunction(functionString){
    		eval(functionString);
    	}
    The function is created successfully, but now it is scoped localy and available only inside the function. Is there a way to make the function available globaly like you can do with a variable?

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,861
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    Move it outside of the other function.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    SitePoint Evangelist comfixit's Avatar
    Join Date
    Dec 2004
    Location
    Pasadena
    Posts
    537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well if need be I could put some sort of loop at the top level to accomplish this, but I really think that encapsulating everything inside of a function is cleaner. But I guess it becomes sloppy again when I destroy scope and make things global.

    If anyone knows how to make a function declared within another function global I would be interested in knowing, otherwise it will have to exist at the top level.

  4. #4
    SitePoint Enthusiast
    Join Date
    Jan 2006
    Location
    Wolsztyn, Poland
    Posts
    60
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What is the format of the function string ? "function name() { .. body ..}" ?
    If yes then you can do something like that:
    Code:
    function loadFunction(functionString){
        /function (\w+)\(/.exec(functionString);
        eval('window.'+ RegExp.$1 +' = '+ functionString);
    }
    If gets function name from the function string and evaluates the code:
    window.function_name = function function_name() { ... }
    which makes the function accessible globally.


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
  •