www.webdeveloper.com
Results 1 to 5 of 5

Thread: Store a Function

  1. #1
    Join Date
    Aug 2006
    Posts
    126

    Store a Function

    Hi all,

    I was wondering if there is a way to store a function? For example, if I called a function like so:

    Code:
    test('dave', 1, 2);
    ...is there a way to store this function along with its variables in something like:

    Code:
    var last_test = function test('dave', 1, 2);
    ...then calling it again later using something like:

    Code:
    last_test.execute();
    Thanks!

    dai.hop

  2. #2
    Join Date
    Jan 2005
    Posts
    350
    Functions are first-class objects, just like any other object, so can be assigned to an object - this is normally referred to as making them a 'method of an object', so there is no need for the ".execute" bit: you just do: last_test();

  3. #3
    Join Date
    Aug 2006
    Posts
    126
    So if I make my function the method of an object what will happen with the variables from the last call? Will they not need to be passed anymore?

    i.e.

    Code:
    test('dave', 1, 2);
    ...would become...

    Code:
    object.test();
    ?

  4. #4
    Join Date
    Jan 2005
    Posts
    350
    That depends on how you _want_ to handle them - for more info have a look at reference material firstly for: "function literal format" and then for "closures"

    You can either pass the function parameters when you define the function, or when you call it.
    You may want to consider a half-way house, where you do:
    object.methodName = myFunction;
    object.parameters = myParamList;

    That way you get use the function repeatedly, but change the parameters when you need.

  5. #5
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    Code:
    var last_test = function(){return  test('dave', 1, 2); }


    calling it again later:
    Code:
    last_test();

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles