Reputation: 69
How can I access a variable inside a function which is inside a function in javascript ?
var a;
var surveyObjects = Parse.Object.extend(surveyObject);
var query= new Parse.Query(surveyObjects);
query.count({
success: function(count){a = count;},
error: function(error){}
});
alert("count of function "+a);
a
is showing undefined
value. I need to use the value of a
outside.
Upvotes: 6
Views: 76181
Reputation: 11
use return statement to access variables globally.
function(){
var k=1;//local
return k;//global
}
result=k+10;//sample
Upvotes: 1
Reputation: 345
// You can simply do it by
function test()
{
this.name='xyz';
}
var obj = new test();
console.log(obj.name);
Upvotes: 7
Reputation: 1188
like it:
function one() {
this.two = function () {
var a = 10;
return a;
}
}
var o = new one();
alert(o.two());
Upvotes: 1
Reputation: 69
Thanks. I declared the variable as global and inserted value inside the inner function and then made a function call inside the function to trigger another function which call the value.
var a=0;
var surveyObjects = Parse.Object.extend(surveyObject);
var query= new Parse.Query(surveyObjects);
query.count({
success: function(count) {a =count; total();},
error:function(error){}
});
function total(){alert (a);}
Upvotes: 0
Reputation: 91555
Because of how javascript, and most languages, scope variables, you can't access variables declared inside a function from outside a function. The variable belongs to the function's scope only, not the global scope.
Fortunately, functions inherit the scope of their caller. So the easiest way to make your variable accessible from outside the function is to first declare outside the function, then use it inside the function.
function one(){
var a;
function two(){
a = 10;
return a;
}
return a;
}
Note that you should be very careful about how you scope your variables. The whole point of functions is to encapsulate and isolate functionality.
In the case of promises, you can declare a variable outside the promise and then set its value on success.
var a;
Parse.doSomething().then(function(data) {
a = data;
});
EDIT: Based on what you showed in the comments, you're having async issues. Promises are asynchronous meaning they don't run in sequence in your code. That's why the success
and error
callbacks exist, to be called once the promise resolves. Your alert(a)
is outside the promise callback, so it runs immediately, without waiting for the Parse promise to resolve so a
is still undefined. If you put the alert(a)
inside the promise callback, a
will have been set by that point.
var a;
query.count({
success: function(count) {
a = count;
alert(a);
return a;
},
error: function(err) {}
});
Upvotes: 8
Reputation: 700
You can do this by using implicit global variable behaviour.
function one(){
function two(){
a=10;
}
two();
}
one();
console.log(a);
If you don't declare a variable in javascript I.E not using the var
keyword it becomes a global variable.
for further reading:
Upvotes: 5