Access closure variable [duplicate] - javascript

This question already has answers here:
How to access javascript variable stored in function closure from browser console?
(2 answers)
Closed 9 years ago.
I have a feeling I know the answer to this question, however is there anyway to view the current value of inside via console?
var test = (function() {
var inside = 0;
return function() {
inside++;
console.log(inside);
return inside;
}
})();

Just call test() and console.log will print the value.
Your closure is self invoked but your inner method is just returned so it is never called in your example.
You should use:
var test = (function() {
var inside = 0;
return function() {
inside++;
console.log(inside);
return inside;
}
})();
test();//Will print 1
So it will create the closure and your return statement will put the inner function in the variable test. So your test became the inner function. Then you need to call it.

Related

How to get the scope from where a function was called? [duplicate]

This question already has answers here:
How to access values from <function scope>'s Closure in Chrome Developer tool's Watch panel?
(2 answers)
What way (if any) can I get the reference to anonymous function's closure in javascript?
(3 answers)
Is it possible to gain access to the closure of a function?
(4 answers)
Closed 5 years ago.
I'm trying to create a javascript expression parser, able to parse an expression and get the declared variables in its body, without executing the function:
function test(expressionFn) {
var expression = getExpression(expressionFn);
// get value expression.expressionRight in scope
// not work -> var valueRigthInScope = expressionFn.prototype.constructor[[[Scopes]]][expression.expressionRight];
console.log(expressionFn.prototype); // see ".constructor[[[Scopes]]]" in debug tools [F12]
}
function getExpression(expressionFn) {
var strAfterReturn = expressionFn.toString().split("return")[1].trim();
let strExpression = strAfterReturn.split(";")[0].split(" ");
return {
expressionLeft: strExpression[0],
operator: strExpression[1],
expressionRight: strExpression[2]
};
}
function start(){
var myValue = "This is value!";
test(function(x) { return x.prop1 == myValue; });
}
start();
<h1>See console</h1>
Example in JsFiddle.
But I can not access the scope of the function to get the value of the variable myValue, for example.
In the Google Chrome console I managed through the function to get the scope where the variable myValue is declared, but I can not access that same scope in javascript.
Follows the image of the Google Chrome console:
How can I access [[Scopes]] in the image?

'var a' vs 'this.a' in function block [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
What is the scope of variables in JavaScript?
(27 answers)
Closed 5 years ago.
I tried to search it on internet but didn't got any answer. Why access of two variables before declaration have two different outputs:
function test() {
console.log(a); // prints 'undefined'.
console.log(b); // prints 'b is not defined'.
var a = 5;
this.b = 10;
}
when you declare var variable inside the function then that variable is limited to that function. That mean scope of that variable is limited to that function so you can't access that variable outside of that function.
But if you use this then it can be access through outside but then again you need to create a object of that class/function and access trough it.
function test() {
var a = 5;
this.b = 10;
this.printB = function(){
return this.b;
}
this.printA = function(){
return a;
}
}
var obj = new test();
console.log(obj.a)
console.log(obj.b)
console.log(obj.printA())
console.log(obj.printB())
when you write a variable with var like var a it become a function
level variable. so now a is a variable which is present there before consol.log(a) and its not given a value so its undefined for b there is no variable defined with name b before it called.
And which all variables are defined with var will be function level variable and will be created before anything else in the function. so a will be present in the function at the starting itself.
and here this will be holding the object of Windows.
First of all, you are trying to examine the variables before you declared them.
This is the correct order:
function test()
{
var a=5;
this.b=10;
console.log(a); // Should print 5
console.log(b); // Should print undefined
console.log(this.b); // Should print 10
}
Second, regarding your question, declaring a var inside your function, make is a local private variable inside your function.
declaring this.b, will cause b to be in a different scope, and b for itself as undefined. If you want to use b inside the function, use this.b.

Javascript Closure -Local variable nested function [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 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.

Don't understand how Closure Functions are working? [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 6 years ago.
I am reading eloquentjavascript to learn javascript but this closure thing is confusing me. warp1 is not function but it looks like function and it looks like taking argument too. How do closure functions work ? and what are the reasons we can use it ?
function wrapValue(n) {
var localVariable = n;
return function() { return localVariable; };
}
var wrap1 = wrapValue(1);
var wrap2 = wrapValue(2);
console.log(wrap1());
// → 1
console.log(wrap2());
// → 2
The outer function (wrapValue) returns a function. So the returned function gets assigned to your variables wrap1 and wrap2. That's why you can call the returned function from your variable.
Maybe it's easier to understand when we look at the following.
You can create a function like you did:
function foo() { return "foo"; }
Or you can assign a function to a variable:
var foo = function() { return "foo"; }
The second example basically does exactly the same as your closure does - it assigns a function to a variable.
In all cases, you can call the function with
foo();
Either by variable, or function name.

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