views:

138

answers:

5

Hi,

  1. I have declared a local variable named cont in a function named validate.
  2. I am calling a function process from inside validate.
  3. I am sending the string 'cont' as argument to validate function.
  4. In the process function using the string 'cont' i want to access the javascript local variable's value like window['cont']. But i get undefined.
  5. What i am trying to do is trying to access variables like $GLOBALS in php or $$.

Here is an example of what i did.

<script>

function process(str)
{
   alert(window[str]);
}

function validate()
{
   var cont='once there lived a king named midas';
   process('cont')
}

validate();

</script>

The reason is i do most of the forms as ajax. i dont want to make a request string like this.

var param = "command=insert&content=" + encodeURIComponent(cont);

i want to do like this.

var param = makeParam('command,[insert],content,(cont)');

what i do in makeparam is i use regular expression to extract key value pairs. so i get the string cont from (cont) and i substitute it into window variable like window[cont]. cont will have the string 'cont'.

so how do we get the content of a variable by using the name of the variable as string?

so i am looking for javascript equivalent of php's $$

Edited

a part of the code where i extract cont which is inside (cont) which means i want the content of the string between ().

nxt = str[i+1].match(/\((.*)\)$/)

if(nxt)param += '=' + encodeURIComponent(window[nxt[1]]);

the content of param would be

"command=insert&content=once there lived a king"
// assume that once there lived a king is encoded

Edit. Note2.

After few more responses i am editing the code to add this.

I am trying to do like $GLOBALS in php.

I haven't tried whether $GLOBALS would cantain local variables too.

and learned that local scope will not come into $GLOBALS.


Update after reading Felix King's Update.

I want to use a function which will construct a query string as simpler as possible. like the following.

var param = makeParam('command,insert,/title/,/keywords/,/description/,mode,[1],fckcontent,(cont)');

// if it is a text without // or () then the it is a straight key value pair. so i will do comment=insert.

//if it is /title/ then the key is title and its value is an input elements value with id as title so title=getElementById('title')

//if it is mode,[1] then mode is the key and 1 is its direct value//

//if it is fckcontent,(cont) then fckcontent is the key and cont is a javascript local variable which will contain html content from a WYSIWYG editor.

// a sample result will be

 var param = "command=insert&keywords=somekeywords&description=somedescription&mode=1&fckcontent=<p>once there lived a king<p>

and then casablanca stated that $GlOBALS will not contain local scope variables and that is the same way in javascript. that's right.

+1  A: 
function validate()
{
   var cont='once there lived a king named midas';
   process('cont')
}

cont is defined in the local scope of the function, not in global scope. Either do just

cont='once there lived a king named midas';

(without var) or

window.cont='once there lived a king named midas';

Update:

But why do you want to go through so much trouble with parsing strings? Why don't you do:

var param = makeParam({command: 'insert', content: encodeURIComponent(cont)});
Felix Kling
Yeah instead of using it as a global variable we can use like yours. nice. still, is there any other alternate? even if am thinking about something like $GLOBALS then yours is the way. besides, just thinking aloud for other alternatives. thank you.
Jayapal Chandran
i am answering this after your update. i want to do it like this. please refer my question under the bold section "UPDATE after reading Felix King's update".
Jayapal Chandran
aah. after all these discussions i have concluded. i am going to use your way. window.variable. thank you. for some time let us see other peoples answers so that i could make this post more stronger.
Jayapal Chandran
A: 

I'm trying to understand why you need to pass the variable as a string and why you want to access cont via the window object. This does what it looks like you expected your code to do:

process = function (str) {
    alert(str); // This will alert 'once there lived a king named midas'
}

validate = function () {
    var cont = 'once there lived a king named midas';
    process(cont);
}

validate();

FYI: It is generally considered bad practice to declare global variables, especially in a case like this where you don't appear to need them. (I could'd we wrong, though; I'm not entirely sure what you're trying to accomplish)

Edit: I would suggest using some functions and passing some variables around rather than mucking around with eval()-esque variable references. For example, you could implement makeParam like so:

var cont = 'Boggis, Bunce, and Bean.',
    makeParam = function(str) {
        var param = '',
            i = 0,
            arg = str.split(','),
            l = arg.length;
        while (i < l) {
            if (arg[i + 1].match(/\([a-zA-Z]+\)/)) { // No reason to capture
                param += [arg[1], cont].join('=');
                i += 2;
            } else if (arg[i].match(/\/[a-zA-Z]+\//)) { // No reason to capture
                param += [
                    arg[i], 
                    document.getElementById(arg[i]).value
                ].join('=');
                i += 1;
            } else {
                param += [arg[i], arg[i + 1]].join('=');
                i += 2;
            }
            param += (i + 1 === l) ? '' : '&';
        }
        return param;
    };
param = makeParam('command,insert,/title/,/keywords/,/description/,mode,[1],fckcontent, (cont)');
param === 'command=insert&\
         keywords=somekeywords&\
         description=somedescription&\
         mode=1&\
         fckcontent=Boggis, Bunce, and Bean.';

But you'd probably want to pass cont into your makeParam function.

indieinvader
i am trying to do like $GLOBALS in php. i hope it would work for local variables like in php. isn't it? oh. does $GLOBALS include local scope? and i have clearly stated the reason for such a need.
Jayapal Chandran
I have added a little of the code which i use to form a query string under the bolded text Edited.
Jayapal Chandran
For one your question was pretty ambiguous when I read it, two JavaScript **is not** PHP so don't treat it that way: use JS idioms and best practices, three your third comment is/was unnecessary and very irritating.
indieinvader
Also, I feel like you're asking two questions.
indieinvader
Thank you. comment deleted. i have my function like yours. the only option i was wondering was accessing local variables as window['name'] and since variables in local scope are not referred by window object i am going to use it like a global variable with the help of window object. anyway think you i will cross check my function with yours and will take the options which are needed. my function is here http://vikku.info/codetrash/General.js#MakeParamEx
Jayapal Chandran
+1  A: 

Your code is correct, but what you're expecting is wrong. $GLOBALS in PHP does not include local variables, and the same thing applies to window in JavaScript. cont is local to validate, so obviously it can't be accessed from process.

In PHP, you need to explicitly declare a variable as global inside a function. In JavaScript, it works the other way round: any variables declared using var are local, anything that is not declared is global.

casablanca
ah, yes i was assuming that too. nice point. won't we get errors for undeclared local scope variables. what i am thinking to do is just assigning value to an undeclared local variable. i hope it should work. isn't it?
Jayapal Chandran
Yes, that will work, and you won't get any error. Any variable that you don't declare is assumed to be global.
casablanca
ok. thank you. now every thing is clear. yet, having hard feeling for using additional global variables for these purpose.
Jayapal Chandran
You could use a single global object for storing parameters, instead of several variables. Just define an empty object at the beginning, say `globals = {};`, and then you can use `globals['cont']` instead of `cont`.
casablanca
+1  A: 

As others have suggested, you wont be able to access variables in local scope elsewhere in your code.

The code you originally posted was:

function process(str) {
    alert(window[str]); // This will alert 'once there lived a king named midas'
} 

function validate() {
    var cont = 'once there lived a king named midas';
    process('cont'); 
}

validate();

Another option (rather than putting everything in the 'window' variables map), is to create your own map.

So your code would become:

var variables = { }

function process(str) {
    alert(variables[str]); // This will alert 'once there lived a king named midas'
}

function validate() {
    variables['cont'] = 'once there lived a king named midas';
    process('cont');
}

validate();

All this is doing is creating a global map which you can add to and index using strings.

David_001
yes. nice. thank you.
Jayapal Chandran