I'm trying to call this variable outside the function but I get undefined as a result. I understand without var the variable could be called in global scope but i get undefined. I also tried setting the var outside the function and calling it but no success also. Here's my simplified code thank you :)
function function1() {
$.getJSON('random.json')
.success(successfunction)
.error(failfunction);
function successfunction(data) {
testvar = (data.name);
}
function failfunction(error) {
console.log(error);
}
};
console.log(testvar);
used
$( document ).ajaxStop(function() {}
to load the var after ajax load.
It's just visible in the method scope, you have to declare it outside the function (which means global in this case) or return it in the function call:
var testvar2 = "var 2";
function function1() {
// parse json
return successfunction("data");
function successfunction(data) {
testvar2 = "var glob";
var testvar = "var ret";
return testvar;
}
function failfunction(error) {
console.log(error);
}
};
console.log(testvar2);
console.log(function1());
console.log(testvar2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Declaring global variables should be avoided and is not good practice, try to define the scope of a variable as small as possible. If any other js module also declares a varibale named testvar2 funny things might happen.
if you want global scope attach your variable to global object like window
function successfunction(data){
window.testvar = "var";
}
By that you will be sure that it becomes global .
However, you should note that successfunction is a callback that will be running later on : it is running after timeout & only if the ajax call succeeded .
try adding a return testvar in suc cessfunction instead of calling testvar
call the successfunction
function successfunction(data){
testvar = "var";
return testvar;
}
Related
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.
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) {}
});
// You can simply do it by
function test()
{
this.name='xyz';
}
var obj = new test();
console.log(obj.name);
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:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/var#Implicit_globals_and_outer_function_scope
like it:
function one() {
this.two = function () {
var a = 10;
return a;
}
}
var o = new one();
alert(o.two());
use return statement to access variables globally.
function(){
var k=1;//local
return k;//global
}
result=k+10;//sample
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);}
function coolo()
{
var tile1 = -1;
var tile2 = -1;
$(".grid-cell").click(swap);
}
function swap()
{
console.log(tile1)
}
coolo();
Of course I will get a Uncaught ReferenceError: tile1 is not defined error. I can fix it by passing the variable to the function or putting the variable in global scope. Is there a way for the swap function to access variables in the scope of coolo? I can access variables in global scope, so why not this? I've tried using the this keyword, but jquery assigns this to the dom element that has been selected. I'm not sure if using this would work in a non jquery situation either. If there isn't, I'd like to learn more about how scoping works in javascript.
You will have to pass an argument to that function, but you can make it little bit more generic
function coolo()
{
var tile1 = -1;
var tile2 = -1;
$(".grid-cell").click(function(){swap(title1)});
}
function swap(title)
{
console.log(tile)
}
coolo();
You want to know about scope, this will work. As you only use swap inside coolo, there's no reason not to put swap inside the coolo function, thus in the same scope as tile1
function coolo() {
var tile1 = -1;
var tile2 = -1;
var swap = function () {
console.log(tile1)
}
$(".grid-cell").click(swap);
}
coolo();
Define it as global variable outside these two function or use window.title
var title
function A(){
}
function B(){
}
or pass it as a parameter to the second function
function A(){
B(title);
}
how can I declare,set and access global variable from one function to another?
var testvar;
$(document).ready(function(){
test1();
});
function test1(){
return testvar;
}
function test2(){
var a = "Hellow World";
testvar = a;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The code above was just my sample to make it easy to understand on what I am trying to do. This is just for educational purposes. I just want to get the result in that way. Or is there a way to set a Global variable within a function and use it to another function outside that function?
What do to?
Creating variables in the Global scope is very bad practice. You shouldn't do it because it can cause conflicts especially in future JavaScript versions.
You can run the functions from a scope or object, try:
var shared = {};
$(document).ready(function () {
test1.call(shared);//undefined
test2.call(shared);
test1.call(shared);//foo
});
function test1 () {
alert(this.testvar);
}
function test2 () {
var a = 'foo';
this.testvar = a;
}
How it works
In simple terms, this will store all the variables in the object (shared). You can declared a "shared variable" by using this. instead of var. By using .call() we can choose to run the function in the scope of the object. I'm not the best at explaining, learn more here
Fiddle
Global Variables are always accessible from everywhere. But this might help you understand it better:
var testvar;
$(document).ready(function(){
console.log(testvar); // outputs: undefined
test2();
console.log(testvar); // outputs Hello World
console.log(test1()); //outputs Hello World
});
function test1(){
return testvar;
}
function test2(){
var a = "Hellow World";
testvar = a;
}
var testvar;
$(document).ready(function(){
test1();
});
function test1(){
return test2();
}
function test2(){
var a = "Hellow World";
testvar = a;
}
console.log(testvar);
test2() is not called. It needs to be called in order to redeclare the variable
https://jsfiddle.net/uwzapwrk/
I use this method and it works for me
function somefunctionname(){
// Some action
anotherfunctionname(put_your_value);
}
function anotherfunctionname(put_parameter_as_you_want){
var some_var = put_parameter_as_you_want;
// Some action with your var
}
This method work after somefunctionname() was execute and you can execute the anotherfunctionname() with variable was store on somefunctionname()
I've wrapped all my functions around an immediately-invoked function expression as shown:
(function(){
"use strict";
function toggleComment(parentCommentID) {
$("form#" + parentCommentID).toggle();
}
function scrollBottom() {
window.scrollTo(0, document.body.scrollHeight);
}
})();
However, upon calling one of these functions through a link:
Reply
The Chrome console outputs Uncaught ReferenceError: toggleComment is not defined. Am I mistaken in thinking that an immediately-invoked function expression, as its name suggests, should be invoked immediately and therefore toggleComment should be called? Should I call the function differently?
The function toggleComment is not visible. It's enclosed in the ready function you're using; if you want to be able to call it like that (which is not recommended, in most cases), you have to hoist it outside of that function and make it globally accessible.
And this has nothing to do with strict. If you remove the strict line, this problem will still be the same.
The functions are no longer declared in the global scope. Try
window.toggleComment = function(parentCommentID) {
$("form#" + parentCommentID).toggle();
};
You have declared the functions inside a closure. They're outside of the scope of the HTML tag.
You could set an id to your <a> tag as well as publish your function to the global scope, so you can do this:
(function(){
"use strict";
var toggleComment = function(parentCommentID) {
$("form#" + parentCommentID).toggle();
}
function scrollBottom() {
window.scrollTo(0, document.body.scrollHeight);
}
document.getElementById("yourATagId").onclick(function() {
toggleComment(159);
});
window.toggleComment = toggleComment;
})();
Maybe you could benefit from this simple singleton pattern:
(function() {
var controller = {};
controller = new function() {
this.sampleProperty = "my property";
}
controller.yourFunction = function() {
var localVariable;
console.log("I can access " + this.property);
};
window.controller = controller;
})();
This way, controller will be known to your global scope.
I have this....
function MyFunction() {
var myVar = "I think I am encapsulated";
this.getMyVar = function() {
return myVar;
}
}
var myProperty = new MyFunction();
console.log(myProperty.getMyVar());
myProperty.myVar = "you're not encapsulated";
console.log(myProperty.getMyVar());
It outputs: "I think I am encapsulated twice". Why? I did not think this was a closure...
The closure is around the "getMyVar" function. The variable "myVar" inside the constructor is a local variable, and not visible outside the function except as the return value from "getMyVar".
Setting a "myVar" property on the object does just that, but the "getMyVar" function is not returning a property of an object; it's returning the value of the local variable in the closure.
Yes, it is.
When you define a function inside of another function, the inner function has access to all of the outer function's local variables...
In your case, getMyVar has access to myVar - through the closure.
var myVar = "I think I am encapsulated";
this.getMyVar = function() {
return myVar;
}
This is a closure, and the myVar variable from the time the function was created will be returned. Notice that's it a local variable, so there's no other way to access it after this function exits.
var myVar = "I think I am encapsulated";
Notice that this is not this.myVar (the variable you're setting later with myProperty.myVar).
Probably what you're trying to do is:
function MyFunction() {
this.myVar = "I think I am encapsulated";
this.getMyVar = function() {
return this.myVar;
}
}