var myVar = 5;
var example = function() {
var myVar = 10;
// How can I access the global variable 10?
};
If there is a global variable with the same name as a local variable, how can I access the global one?
I am not using es6.
I am running it in jsdb, not a browser or node so I do not have access to objects 'Window' or 'global'
Assuming you can alter the code calling your example() function, you should be able to pass the current scope using Function.prototype.call() and access it using this. For example
'use strict'
var myVar = 5;
var example = function() {
var myVar = 10;
console.info('Local:', myVar)
console.info('Outer:', this.myVar)
};
example.call({ myVar })
Related
This question already has answers here:
Surprised that global variable has undefined value in JavaScript
(6 answers)
Closed 1 year ago.
I have a block of code and I want to exactly know the running order and why the result like this:
var variable = 10;
(()=>{
variable_3 = 35;
console.log(variable_3);
var variable_3 = 45;
variable_2 = 15;
console.log(variable);
})();
console.log(variable_2);
console.log(variable_3);
var variable=30;
The output for this code is
35, 10, 15, Error
What I understand is:
inside the IIFE we create a global variable_3 and assigned 35.
Then it print out 35.
We create a Var variable_3 inside the IIFE and assigned 45. (Is this Var get hoisted out of the IIFE??)
35.10.15 I understand, can you explain the last number and make my logic correct?
Thanks!
(()=> {
a = 123;
console.log(a); // 123
console.log(window.a); // undefined
var a;
})();
(()=>{
var a = 4;
(()=>{
console.log(a); // undefined
var a = 5;
})()
})()
(()=>{
var source = {};
(()=>{
a = source;
var a;
console.log(a === source) // true
// The variable source is indeed assigned to variable a, although variable a is declared after
})()
})()
var variable is a definition
like function ,
function can use before defined;
main();
function main(){}
so
a = 1;
var a;
like function; use variable before define is also ok;
1.)Basically there are two scopes, that is the local and global scope. The function
scope falls within the local scope.
2.)Hoisting moves declarations to the top of the current scope.
3.)If you assign a value to a variable you have not previously declared, it is automatically declared as a global variable(even if it is within a function) and initialized with the assigned value.
4.)In the local function scope, declaring with var, let or const keywords will all create a local variable. It is only available or accessible within that function.
In your case:
var variable = 10;//global variable declaration, outside the function.
(()=>{
variable_3 = 35;//declares a global variable, ref. (3).
console.log(variable_3);//prints 35, because it is available globally now.
var variable_3 = 45;//re-declaration turns it to local variable, ref. (4).
variable_2 = 15;//declares global variable, ref. (3)
console.log(variable);//prints 10, because it is a global variable.
})();
console.log(variable_2);//prints because it is a global variable
console.log(variable_3);//fail to print because of re-declaration which changed it from a global variable to local function variable.
var variable=30;
Let say we declare a variable in the global context, like so:
var someVariable = "someValue";
We can always access its value like window['someVariable'] as it is in the global execution context.
But, how can we access it value the same way if it is inside some function and not in the global execution context? For e.g.
function someFunction(someParameter) {
var someVariable = "some value";
// some code
}
I want to do something like someFucntionContext['someParameter'] or someFucntionContext['someVariable'] to access the value of those variables in the execution context of the someFucntion like I just did for the variable declared in the global context.
That's not possible without returning objects or instantiating the function and accessing the property.
Global variables are automatically a property of the window object, provided you use var and not let or const. Such as root level functions being automatically a method of the window object. But functions do not behave like primitive objects. You need to do something like
function Favorites(){
return{
food: "burrito",
color: "gray"
}
}
var fav = Favorites();
var favfood = fav.food; //fav['food']
OR
function Favorites(){
this.food = "burrito";
this.color = "gray";
}
var fav = new Favorites();
var favfood = fav.food; //fav['food']
And like so
var favfood = window.fav.food;
var favcolor = window['fav']['color']
One of the approach could be exposing certain properties of the function itself.
function fn(){
fn.num = 100;
}
//access fn.num
console.log(fn["num"])
You can control which properties you want to expose from the function itself. For example,
function doSomething(num, addStr){
//expose num
doSomething.num = num;
var str = "Hello ";
if(addStr){
str += addStr;
}
//expose str
doSomething.str = str;
}
//set num
doSomething(100);
//access num
console.log(doSomething.num)
console.log(doSomething["num"])
//set num and str
doSomething(200, "Jerry!")
//access str
console.log(doSomething["str"])
I have the following closure:
var Container = (function () {
var variable;
var changeVariable = function () {
variable = 5;
};
return {
variable: variable,
changeVariable: changeVariable
};
})();
Container.changeVariable();
console.log(Container.variable);
The result is undefined, unless I set variable as:
Container.variable = 5
Why is that so? What's the difference? How should I do this properly?
Why is that so?
JavaScript assigns by value.
variable = 5; assigns the value 5 to the variable variable.
variable: variable, assigns the value of variable (at the time the code runs) to the property variable. It does not create a reference to the variable called variable.
When you later change the value of the variable called variable, you don't change the value of the property called variable.
How should I do this properly?
Create an object. Store the object locally. Manipulate that object. Return that object.
Forget about having the variable called variable entirely.
var container = (function() {
var self = {
variable: undefined,
changeVariable: changeVariable
};
function changeVariable() {
self.variable = 5;
}
return self;
})();
container.changeVariable();
console.log(container.variable);
(Aside: Convention reserves identifiers beginning with capital letters for constructor functions. I've renamed Container to follow that convention).
Use a getter:
return {
get variable() { return variable; },
changeVariable: changeVariable
};
I am currently learning node.js and already meet several times the same problem that seems very simple but I can't still understand how to solve it.
Code:
var SRC_PORT = 6025;
var dgram = require('dgram');
var clientUDP = dgram.createSocket("udp4");
var test
clientUDP.bind(SRC_PORT, function () {
multicastNew()
});
function multicastNew() {
var test = 777
console.log(test);
}
Problem
Cant use variable test content outside the function multicastNew()
In the function multicastNew() I have a variable var test. In that function multicastNew() I gave to test = 777. When I want to console.log(test) in the same function multicastNew() everything works,it outputs 777. The problem is that when I want to console.log(test) outside function multicastNew() it outputs undefined.
Can you please explain me how to solve this issue and why it is.
Thank you!
You should change var test = 777; to test = 777; in mulitcastNew(). Your code should be as such:
var SRC_PORT = 6025;
var dgram = require('dgram');
var clientUDP = dgram.createSocket("udp4");
var test;
clientUDP.bind(SRC_PORT, function () {
multicastNew();
});
function multicastNew() {
test = 777;
console.log(test);
}
A note on scope. In Javascript, functions create scope. Any variable defined with var inside of a function is a local variable, invisible outside the function. It's only local to the wrapping function, and if there is no wrapping function, it becomes a global variable.
Consider the following:
//this is global scope
var a = "Chris";
var b = "Inspired";
function nameChange(){
var a = "inspired"; // local to the function nameChange()
b = "Chris"; //without var we are changing the global variable
console.log(a); //will output inspired
}
nameChange(); // inspired
console.log(a); // Chris
console.log(b); // Chris
It's all about function scope. When u declare var test = 777, then u are creating new variable in scope of your function multicastNew(). This variable covers your 'main' variable from the global scope... So your function works from now on your local variable, not on the one from the global scope. JavaScript always look for variables inside scope it is called. In your example, when u try to call test outside the multicastNew(), then current scope is GLOBAL, so it finds your var test from the begining of your code. It's always work from inside to outside (closures). You can read:
Scopes
I have a global variable:
var chart;
A function which creates the chart:
function setChart(variableName, chartContainer){
variableName = new CanvasJS.Chart(chartContainer, {**params**});
variableName.render();
};
I call setChart
setChart(chart, "chartContainDiv");
If I call chart.render(); later, it doesn't work.
How can I achieve this? / What am I misunderstanding?
Since you're passing a string into the function, you end up trying to assign this:
setVar("globalVar");
// In setVar...
"globalVar" = 5
which obviously doesn't work. Passing in just the variable name itself will almost work as expected:
setVar(globalVar);
// In setVar...
globalVar = 5
HOWEVER
Because of variable scope, inside the setVar function you have a local variable with the same name as the global one. Doing any assignation here will just set the local variable to 5, where the global variable will remain at whatever value it used to be.
var myVar = 1;
function setVar(globalVar) { globalVar = 5; alert(globalVar); }
setVar(myVar); // alerts 5
alert(myVar); // alerts 1
Interestingly, if you pass the string in then you're able to set it via array-access on the window object:
setVar("globalVar");
// In setVar...
window[variableName] = 5; // window["globalVar"] = 5;
but trying to do that by passing the variable itself in doesn't work...
setVar(globalVar);
// In setVar...
window[globalVar] = 5; // window["5"] = 5 // or whatever globalVar contains
The TLDR version of this is that this is the only way to do this exactly as you're trying to do in the OP (although there are other ways such as Ahmad's answer, where you set a specific variable without passing it):
var myVar = 1;
function setVar(varName) { window[varName] = 5; }
setVar('myVar');
Use the function as a factory that returns a chart object, instead of passing it an empty variable. This uses the exact same concept, by creating an object and then returning that object, but it doesn't use a CanvasJS object for simplicity purposes:
function setChart(chartContainer) {
var variableName = new String(chartContainer);
return variableName.toUpperCase();
};
var chart = setChart("chartContainDiv");
var chart2 = setChart("blahBlah");
console.log(chart.toString()); // "CHARTCONTAINDIV"
console.log(chart2.toString()); // "BLAHBLAH"
http://jsfiddle.net/n8Lg4wqy/3/
first you have to be clear on the scopes of variables and global variables. In you example, there is no line where you set globalVar to 5. You only set a local variable for the function setVar called variableName to 5.
what you should do is:
var globalVar;
function setVar(){
globalVar = 5;
};
now if you want to have a global variable or a set of global variables then you should have them in an object and then have a function that take that variable name and an optional value that you to assign.
var globalVariables = {"globalvar1" : "", "globalvar2" : "", .... };
function setGlobalVar(variableName, Value) {
globalVariables[variableName] = value;
}
setGlobalVar ('globalvar1', 5); // this would do it