Javascript Closure -Local variable nested function [duplicate] - javascript

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I am trying to use a variable x defined inside a function P whose value I am trying to set in another function. It always comes undefined.
I tried applying my mind to use closure but it's just going off my head. It does not gives me a string rather a object.
The logic is as follows.
function P(i){
var x;
if(i!=null){
//this pulls the data correctly and i could see it in network tab response.
var dataFromQuery=widgets.DATA.create({
url:"abc/cde",
queryTemplate :"/query"+i+ "?"
});
//we query the data and set the value as per the logic.
dataFromQuery.query(function(data){
if(data[0].name){
x=data[0].name; // this stays undefined , and i understand this is a new local variable x.Also the value is here and comes fine here so no issues with the data but i want to set it to the variable defined outside as x.
}
})
}
else{
x="somehardcode";
}
};
I have tried storing the result dataFromQuery.query(function(data){ to a var and then setting it to x but it again comes as a object, which i need as a string.
Thanks

I think you're looking for something like this:
var P = (function() {
var x;
function _P(i) {
//your internal logic here
}
return _P;
})();
Both xand _P are wrapped in the enclosure and scoped only to the auto-executed anonymous function. _P is returned and available as var P in the outer scope, but x will remain hidden.

Related

Lifetime of local variables inside an Object Constructor Function [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 7 months ago.
In this example, taken from the W3Schools JS Tutorial, how is it possible for the variable n to still be used in the next function ?
// Home Made Iterable
function myNumbers() {
let n = 0;
return {
next: function() {
n += 10;
return {value:n, done:false};
}
};
}
// Create Iterable
const n = myNumbers();
n.next(); // Returns 10
n.next(); // Returns 20
n.next(); // Returns 30
I'm coming from a C/C++ background and the lifetime of this variable makes no sense to me. It seems to behave like a global static variable but it should have been deleted when exiting myNumbers(), especially when declared with the let keyword. How can, then, the next method uses it without raising a ReferenceError and keeping its value updated ?
Because of a closure feature of the JavaScript, keep the variable accessible even if the containing function died, whenever there is a child function still need to access it.
For more resources.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

JavaScript function not working when passing variable instead of hard coded value [duplicate]

This question already has answers here:
Using a string to access a variable
(3 answers)
Closed 3 years ago.
I have a JS function as below
// A simple array where we keep track of things that are filed.
filed = [];
function fileIt(thing) {
// Dynamically call the file method of whatever 'thing' was passed in.
thing.file();
// Mark as filed
filed.push(thing);
}
Now, function fileIt(thing) is working well when called as below
fileIt(AuditForm);
Whereas, its giving error at line thing.file(); when i am trying to pass a variable like below
var formID = obj.id;
fileIt(formID);
Variable formID has same value and i.e. "AuditForm" what's wrong here. Kindly suggest.
If obj.id is the string AuditForm, then you have no choice but to use dynamic property notation on the global window object, or use eval if you didn't declare AuditForm with var on the global scope:
If you declare AuditForm with var on the global scope:
fileIt(window[formID]);
If you don't:
fileIt(eval(formID));
Do note that eval is a very poor option, as if obj.id can be interpreted as other code, e.g. another eval call which will be evaluated, then malicious operations can be performed. Example:
const obj = {
id: "eval('alert(\"Inside an eval script!\")')"
};
eval(obj.id);

JavaScript variable returns undefined from inside if / function statement [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 4 years ago.
I don't understand why my global var doesn't work inside of the if statement / function.
myBtn = ["btn01", "btn02", "btn03", "btn04"];
var i;
var btnId;
for (i = 0; i < myBtn.length; i++) {
if (document.getElementById(myBtn[i])) {
btnId = myBtn[i];
document.getElementById(btnId).addEventListener("click", function() {
btnValue = document.getElementById(btnId).value;
btnName = document.getElementById(btnId).name;
});
}
};
console.log(btnValue);
/* Then continue on to use the values from btnValue and btnName */
What its meant to do;
Check if Id on button exists in HTML page
If exist then get the following tags (id=, value=, name=)
Then have the 3 values usable outside of the if statement above.
The console.log(btnValue); displays undefined
I don’t really understand what you are trying to get at here. First of all, you need to declare your variable btnValue outside of the function and then change its value on click. Second of all, when you run this the console log runs first. Console.log is also a function and so it gets pushed to the top. Lastly even if the value changes there is nothing making it console.log again for you to get that value.... you need to register an action to the change. Possibly in the form of an observable. Or at least make it console.log on every click...

javascript global variable undefined when calling the function a second time [duplicate]

This question already has answers here:
JavaScript global variable becomes undefined inside function
(4 answers)
Closed 4 years ago.
var myTimer = 0;
function showChat()
{
$('##ChatArea').toggle();
var v = $('##ChatArea').is(":visible");
if (v == true)
{
var myTimer = 2;
console.log('Turned on ' + myTimer)
}
else
{
console.log('Turned off ' + myTimer)
};
}
So I have this code set up to show a section of the screen and then the same button to close said section. When I open it, I want to set a timer (Removed so as not to confuse people) and use setinterval to store the ID into myTimer (simulated by the "var myTimer = 2"). Even without that part of the code though, it still fails.
So when I open it, the console says "Turned on 2" (working as expected). When I close it, I expected it to be 2 (since I already set the global variable to 2). But what I get is "Turned off undefined".
The global variable is defined (I believe) at the very top. So what am I doing wrong here? Shouldn't turning it off show if not 2, then at least 0?
JavaScript global variable becomes undefined inside function
I didn't think it was within the function, but this is it. Sorry guys. I didn't realize using var sets the variable.. Well, I knew it, but didn't think it would make a local one and remove the global one.
Solution, Change var myTimer=2 to myTimer=2.

javascript variable in closure not showing value assigned when initialized by $(document).ready [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
In my app, I have the following closure. It contains a var, which is initialized in $(document).ready:
var myClosure = (function() {
var thing;
$(document).ready(
function() {
thing = new ClassDefinedInSomeOtherFile();
}
)
return {
thing: thing
};
})();
As the page loads (I debug in chrome), a breakpoint placed in $(document).ready() is reached and I can see thing get assigned to an object of ClassDefinedInSomeOtherFile.
However, elements attempting to subsequently access myClosure.thing encounter errors stating that myClosure.thing is undefined (as do calls from the console to myClosure.thing). If thing was exposed by the return block in myClosure, why does it not reflect the new value assigned to it, when $(document).ready() ran?
Thanks!
you are using IIFE so gets executed immediately and return { thing: undefined}, after that when .ready event triggers, it runs and change thing, but that wont change the returned object, so you would get myClosure.thing is undefined
Solution:
$(document).ready(function() {
var myClosure = (function() {
var thing;
thing = new ClassDefinedInSomeOtherFile();
return {
thing: thing
};
})()
});

Categories

Resources