...

View Full Version : clarification on passing variables



admhays
12-10-2011, 08:14 PM
if i have:

function someFunction(){
var original = "Original Variable";
anotherFunction(original);
}

function anotherFuntion(){
/* 1.does the original variable automatically get passed?
2. will var transformed = original + "Transformed"
give me a result of "Original Variable Transformed"?
3. Or does it have to be declared in the function: anotherFunction(original)
*/
}

thanks for any help

Amphiluke
12-10-2011, 08:27 PM
In your case the original variable's value will be accessible within the anotherFuntion only as a property of the arguments object

function anotherFuntion(){
alert(arguments[0]); // "Original Variable"
var transformed = arguments[0] + "Transformed";
}

Old Pedant
12-11-2011, 07:51 AM
Or does it have to be declared in the function: anotherFunction(original)

It can be. But you could also write the function as


function anotherFunction( frazzlemooper )
{
var transformed = frazlemooper + "Transformed";
...
}

The name of the function argument and then name of the parameter used when the function is called are completely independent of each other.

**********

I would also like to point out that if the variable original had *NOT* been declared inside of someFunction then you could write:


var original; // this declaration is optional

function someFunction(){
original = "Original Variable"; // notice: no var keyword!
anotherFunction( ); // and no argument passed
}

function anotherFuntion(){
var transformed = original + "Transformed"'
}

In this case, you have given the variable original PAGE SCOPE, meaning it is visibile to all functions on the page.

You shouldn't, in general, give page scope to variables unless you really do need them to be "visible" at all times to all functions in the page. But whey you need to, you can.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum