Reputation: 148
How would I make the variables within the function available in the global scope without removing them from the function and so they are logged in the console?
function foo(){
var one = 1;
var two = 2;
}
foo();
console.log(one, two);
Upvotes: 0
Views: 122
Reputation: 583
Sample javascript code for your problem :
<script type="text/javascript" language="javascript">
TestFunction();
function TestFunction()
{
testVariableOne ="Value1";
testVariableSeond = 2;
FunctionToTestGlobalVariables(this);
};
function FunctionToTestGlobalVariables(callback)
{
alert("FirstGlobalVariable" + callback.testVariableOne);
alert("SecondGlobalVariable"+ callback.testVariableSeond);
// Or use like this since they are global now
//alert("FirstGlobalVariable" + testVariableOne);
//alert("SecondGlobalVariable"+ testVariableSeond);
};
</script>
Study scope of function variables from the below link. Reference : http://www.w3schools.com/js/js_scope.asp
var limits the scope to the function in which it is used. So dont use var.
Upvotes: 0
Reputation: 990
use window object to set the property.
function foo()
{
window.one = 1;
window.two = 2;
}
foo();
console.log(one, two);
Upvotes: 0
Reputation: 4047
solution :
function foo(){
one = 1;
two = 2;
}
foo();
console.log(one, two);
example: https://jsfiddle.net/xmm041df/1/
Explanation:
When you use var you are declaring variable for that scope. in your case the function scope.
However when not specifying a scope it will default to the outermost scope. in our case window.
This is not advised though and pollutes the main namespace which is never a good idea.
Upvotes: 1
Reputation: 123513
To access the variables outside of the function, you can declare them outside of it. The function will still have access to be able to assign to them.
var one, two;
function foo(){
one = 1;
two = 2;
}
foo();
console.log(one, two);
Or, if you just need the values, you can have the function return them.
function foo(){
var one = 1;
var two = 2;
return { one: one, two: two };
}
var result = foo();
console.log(result.one, result.two);
Upvotes: 4
Reputation: 27470
Function is an object so you can do for example this:
function foo(){
foo.one = 1;
foo.two = 2;
}
foo();
console.log(foo.one, foo.two);
Or if you want those variables to be placed in global namespace then this:
function foo(){
window.one = 1; // if in browser
window.two = 2;
}
foo();
console.log(one, two);
UPDATE: window.
is used there to avoid runtime errors in strict mode.
Upvotes: 0
Reputation: 1
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
// code here can use carName
function myFunction() {
carName = "Volvo";
// code here can use carName
}
Example taken from: http://www.w3schools.com/js/js_scope.asp
Upvotes: 0