Where do function variables live?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Csaba Gabor

    Where do function variables live?

    I'd like to be able to pass a key1/value1 pair into a function and have
    that function have a local variable by the name of key1 to which value1
    is assigned.

    for example, I'd like to call
    function sample(oOptions ) {
    var key1 = "key1 default";
    var key2 = "key2 default";
    var idx;
    if (arguments.leng th>0)
    for (idx in oOptions)
    window.sample[idx] = oOptions[idx]; // this line wrong

    alert (key1);
    for (idx in window.sample)
    alert(idx + "\n" + window.sample[idx]);
    }

    with sample({key1:"k ey1 was set"}) and have the alert be:
    "key1 was set"
    But the above is incorrect since it sets key1 on the function
    definition (window.sample) and not the instance being invoked.

    How can I fix this up without eval?

    Thanks,
    Csaba Gabor from Vienna

  • Random

    #2
    Re: Where do function variables live?

    I'm not sure how to do exactly what you're trying here, or even if it
    can be done. I'll hope someone posts a more appropriate response.

    Assuming it can't, here's what I'd try:

    function sample( obj ) {
    var key1 = obj.key1 || null;
    var key2 = obj.key2 || null;

    key1 && alert( 'key1 = ' + key1 );
    key2 && alert( 'key2 = ' + key2 );
    }

    Or you might try something like this:

    function sample( arOptions ) {
    var arVars = new Array();

    for( idx in arOptions )
    arVars[ idx ] = arOptions[ idx ];

    alert( 'key1 = ' + arVars[ 'key1' ] );
    }

    Or you might look into making your own object, if it suits your needs
    here.

    I can't make any better recommendations without understanding more of
    your end goal.

    Comment

    • VK

      #3
      Re: Where do function variables live?

      You cannot treat literals (var name) as a strings, no way. You can
      regenerate your function body though:

      <html>
      <head>
      <title>Untitl ed Document</title>
      <meta http-equiv="Content-Type" content="text/html;
      charset=iso-8859-1">
      <script>
      var dynFun = null;
      function dynFunMaker(k, v) {
      dynFun = new Function('var '+k+'=\''+v+'\' ;alert('+k+');' );
      dynFun();
      }
      </script>
      </head>

      <body bgcolor="#FFFFF F" onload="dynFunM aker('myVar','O K')">
      </body>
      </html>

      Comment

      • VK

        #4
        Re: Where do function variables live?

        ....and if study someone's function, you can get dump the function code
        to string:

        var funText = functionName.ar guments.callee || functionName;

        and study the text using indexOf() or regular expressions.

        Comment

        • Csaba Gabor

          #5
          Re: Where do function variables live?

          Csaba Gabor wrote:[color=blue]
          > for example, I'd like to call
          > function sample(oOptions ) {
          > var key1 = "key1 default";
          > var key2 = "key2 default";
          > var idx;
          > if (arguments.leng th>0)
          > for (idx in oOptions)
          > window.sample[idx] = oOptions[idx]; // this line wrong
          >
          > alert (key1);
          > }[/color]
          [color=blue]
          > with sample({key1:"k ey1 was set"}) and have the alert be:
          > "key1 was set"[/color]


          Subsequently, Random wrote:[color=blue]
          > I'm not sure how to do exactly what you're trying here, or even if it
          > can be done. I'll hope someone posts a more appropriate response.[/color]

          ....[color=blue]
          > I can't make any better recommendations without understanding more of
          > your end goal.[/color]


          My goal is just to understand the DOM better as it relates to functions
          and their variables. The background motivation was in thinking about a
          compact way to provide named arguments to javascript functions (which
          is useful if you have a large universe of possible options that you
          aren't expecting to change from default values). The following slight
          modification does what I want (though not bulletproof - nothing ensures
          that all the variables passed in will be local unless I've already
          declared them inside the function with var), but it uses the much
          reviled eval:

          function sample(oOptions ) {
          var key1 = "key1 default";
          var key2 = "key2 default";
          var idx;
          if (arguments.leng th>0)
          for (idx in oOptions)
          eval(idx + " = oOptions[idx]"); // <= eval usage

          alert (key1);
          alert (key2);
          }

          sample({key1:"k ey1 was set"});


          The point is that this is a small piece of portable code which could be
          plunked into any function (just make sure it comes after defaults are
          set). There is no need for customization of the code dealing with
          oOptions on a per function basis. It's up to the caller to pass in
          whatever it would like to override. Still, It would be nice if that
          eval weren't there ...

          Csaba Gabor from Vienna

          Comment

          • VK

            #6
            Re: Where do function variables live?

            > The background motivation was in thinking about a ...

            Well, you can use the fact that any object (including Function) extends
            Object. So you can use Object's hash mechanics in your function:

            function myFunction(k, v) {
            myFunction.k = v;
            // or delete(myFuncti on.k);
            }

            IMHO it's still rather pointless: now you have a new pseudo-var in your
            function, but you have no way to notify function methods what literal
            (var name) to use. You need to regenerate the entire function body (say
            using new Function() method, see my prev posting).

            Comment

            • Michael Winter

              #7
              Re: Where do function variables live?

              On 23/05/2005 02:06, Csaba Gabor wrote:

              [Subject:] Where do function variables live?

              Local variables are properties of a variable/activation object owned by
              every function object. However, this variable object is just a
              specification mechanism: it's described by the specification for
              expository purposes only, and is not something you can access in code.
              [color=blue]
              > I'd like to be able to pass a key1/value1 pair into a function and have
              > that function have a local variable by the name of key1 to which value1
              > is assigned.[/color]

              An alternative to an actual local variable is along the lines of what
              Random posted, only using an Object instance, rather than an Array instance.

              function sample(pairs) {
              var hash = {key1 : 'key1 default',
              key2 : 'key2 default'},
              key;

              if(pairs) {
              for(key in pairs) {
              hash[key] = pairs[key];
              }
              }
              alert(hash['key1']);
              for(key in hash) {
              alert(key + '\n' + hash[key]);
              }
              }

              The object, hash, is obviously not a real hash table (see previous,
              recent debates for reasons and solutions), but it may suffice. It is
              also like any other local; it will be destroyed (usually) once execution
              returns from the function. You could either make it (public) static by
              creating it as a property of the function (similar to what you've done
              already), or private static using a closure of some form:

              var sample = (function() {
              var hash = {key1 : 'key1 default',
              key2 : 'key2 default'};

              return function(pairs) {
              var key;

              if(pairs) {
              for(key in pairs) {
              hash[key] = pairs[key];
              }
              }
              alert(hash['key1']);
              for(key in hash) {
              alert(key + '\n' + hash[key]);
              }
              };
              })();

              The outer function could obviously be an object constructor function if
              sample was meant to be a method.

              [snip]
              [color=blue]
              > window.sample[idx] = oOptions[idx]; // this line wrong[/color]

              sample[idx] = oOptions[idx];

              would be achieve the same thing. Going through the global object is
              unnecessary.

              Mike

              --
              Michael Winter
              Replace ".invalid" with ".uk" to reply by e-mail.

              Comment

              Working...