473,795 Members | 3,231 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

Jul 23 '05 #1
6 1548
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.

Jul 23 '05 #2
VK
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>

Jul 23 '05 #3
VK
....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.

Jul 23 '05 #4
Csaba Gabor wrote:
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);
} with sample({key1:"k ey1 was set"}) and have the alert be:
"key1 was set"

Subsequently, Random wrote: 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.
.... I can't make any better recommendations without understanding more of
your end goal.

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

Jul 23 '05 #5
VK
> 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).

Jul 23 '05 #6
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.
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.
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]
window.sample[idx] = oOptions[idx]; // this line wrong


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.
Jul 23 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
5053
by: Jonas Rundberg | last post by:
Hi I just started with c++ and I'm a little bit confused where stuff go... Assume we have a class: class test { private: int arr; };
38
2787
by: Lasse Vågsæther Karlsen | last post by:
After working through a fair number of the challenges at www.mathschallenge.net, I noticed that some long-running functions can be helped *a lot* by caching their function results and retrieving from cache instead of calculating again. This means that often I can use a natural recursive implementation instead of unwinding the recursive calls to avoid big exponential running-times. Ok, so I thought, how about creating a decorator that...
13
2129
by: Thomas Zhu | last post by:
Hello, I know the difference between the two definations. But I do not know where are they in the memory. would someone tell me ? char s={"good", "morning"}; // at stack? char *t = {"good", "morning"}; // at heap? thanks in advance.
2
1661
by: Sean | last post by:
Hi all, I know that some variables are stored on heaps and some on stack in C++. How about functions? where does function reside on memory? Is it stack or heap? And are both function (not class member) and method (function in a class) stored in the same location (either stack or heap)?
18
33899
by: Jack | last post by:
Thanks.
2
2226
by: Jeff | last post by:
Hello, I assigned a new object to a local variable ("req") in a function (see below). The local variable "req" is obviously destroyed when the function exits, but should the object referenced by the variable live on? It seems that it does (and I want it to), but is this correct? I thought that local variables (and objects) are destroyed when the function exits? I declared a callback function--function () {
23
1969
by: Steven D'Aprano | last post by:
I defined a nested function: def foo(): def bar(): return "bar" return "foo " + bar() which works. Knowing how Python loves namespaces, I thought I could do this:
9
3525
by: tai | last post by:
Hi. I'm looking for a way to define a function that's only effective inside specified function. Featurewise, here's what I want to do: bar_plugin_func = function() { ...; setTimeout(...); ... }; wrap_func(bar_plugin_func); bar_plugin_func(); // calls custom "setTimeout"
0
1094
by: Gerard Brunick | last post by:
Consider: ### Function closure example def outer(s): .... def inner(): .... print s .... return inner .... 5
0
9519
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10435
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10163
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7538
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6779
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5436
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.