javascript callback function from different scope variable not defined - javascript

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);
}

Related

call var in function to outside the function

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;
}

Access a variable inside a function which is inside a function in javascript?

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);}

C++ function prototype equivalent in javascript?

So I want to call function B in function A, but function B is fully declared after function A. I know that in c++ we'd use function prototypes on B, but what about javascript?
code:
markerArray = function() {
// some code here
this.array = [];
this.clearArray = function() {
for(var i = 0; i<this.getLength(); i++)
// for loop code
}
this.getLength = function() {
return this.array.length;
}
// some code here
}
these reason why I put this.getLength below is mainly because my coding style/structure is more readable this way
Javascript doesn't care about this requirement. It will simply work as long as Function A isn't called until after the file is loaded. Function A will be defined, Function B will be defined, then Function A can be called using Function B inside of it with no problem.
Not a problem. Function declarations are hoisted to the top of the enclosing variable environment, so they do not need to be declared in order.
A();
function A() {
B();
}
function B() {
alert('B was called');
}
If you meant something else, you'll need to explain it in your question.
It depends on how you declare your functions. If you declare a function via the Function constructor or a function expression, order matters.
a(1); //this call won't work
//function expression of an anonymous function assigned to the variable multiply
var a = function(i) {
b(i);
}
// b is defined using Function constructor
var b = new Function("i","alert('B was called with ' + i)");
a(1); //this call will work

javascript outer scope question

It is possible to access ther oute scope of a function?
I will explain better.
I've a function, from which I want to acccess its calling function scope.
function called() {
// i want to access the calling outer function scope
}
function calling() {
called();
}
obviusly called() function could be called by a lot of calling functions, and called() has to know time to time which function has called him,` and access its scope variables and functions.
No, that isn't possible.
To access a variable from two functions you need to either:
Declare it in a shared scope
var the_variable;
function called() {
// i want to access the calling outer function scope
}
function calling() {
called();
}
Pass it as an argument
function called(passed_variable) {
return passed_variable;
}
function calling() {
var some_variable;
some_variable = called(some_variable);
}
You should pass any relevant information into called() as parameters:
function called(x, y, z) {
}
function calling() {
var x = getX();
var y = computeY();
var z = retrieveZ();
called(x, y, z);
}
If you expect called to do different things, and receive different contextual information, depending on who calls it, you should probably make it multiple separate functions.
function called(outterScope) {
// outterScope is what you want
x = outterScope.declaredVariable;
outterScope.declaredFunction();
}
function calling() {
this.declaredVariable = 0;
this.declaredFunction = function() { // do something };
var _self = this;
called(_self);
}
No,
if you need to use variables from scope of calling code block (example function)
you have to pass them in arguments
or you can create object and access properties in Object scope (via this.param_name)
Depending on what you want to do, there might be better ways to do it, but if absoultely have to resort to it, you may find that out via Function.caller:
function myFunc() {
if (myFunc.caller == null) {
return ("The function was called from the top!");
} else
return ("This function's caller was " + myFunc.caller);
}
Do note that its not part of the standards, even though some major browsers and IE7 support it.
Also, you cannot access the caller functions scope or variables. Its usability is limited to finding out who called you (helpful for logging or tracing).

Changing a Variable Out of Scope?

Is there any way to change a variable while out of scope? I know in general, you cannot, but I'm wondering if there are any tricks or overrides. For example, is there any way to make the following work:
function blah(){
var a = 1
}
a = 2;
alert(blah());
EDIT (for clarification):
The hypothetical scenario would be modifying a variable that is used in a setInterval function which is also out of scope and in an un-editable previous javascript file. It's a pretty wacky scenario, but it's the one I intend to ask about.
No. No tricks or overrides. You have to plan to have both places be able to see the variable in the same scope.
The only trick I can think of regarding scope is using window in a browser to get to the global object. This can help you get to a "hidden" variable--one that's in scope but whose name has been overtaken by a local variable (or other variable closer in the scope chain).
Closures and classes can afford you some other tricks with scope, but none that allow you to override the scoping rules entirely.
i don't see why you would need to do that, if you need a variable that is accessible from the outside, just declare it on the outside.
now, if you are asking this just because you are trying to learn something, good for you.
var a = 0;
function blah() {
a = 1;
return a;
}
a = 2;
alert(blah());
You can return the value from the function, of course:
function blah() {
var a=1;
return a;
}
But I assume that's not quite what you had in mind. Because a function invocation creates a closure over local variables, it's not generally possible to modify the values once the closure is created.
Objects are somewhat different, because they're reference values.
function blah1(v) {
setInterval(function() {
console.log("blah1 "+v);
}, 500);
}
function blah2(v) {
setInterval(function() {
console.log("blah2 "+v.a);
}, 500);
}
var a = 1;
var b = {a: 1};
blah1(a);
blah2(b);
setInterval(function() {
a++;
}, 2000);
setInterval(function() {
b.a++;
}, 2000);
If you run this in an environment with a console object, you'll see that the value reported in blah2 changes after 2 seconds, but blah1 just goes on using the same value for v.
Functions can access variables declared outside their scope, if they are declared before the function itself:
var a = 0;
function blah() {
a = 1;
}
a = 2;
alert(blah());
Note that your use of var a inside the function declared a local variable named a; here, we omit the keyword as otherwise it would hide a as declared in the outer scope!
No, that will never work, but you could use a global:
var a;
function blah(){
a = 1
}
a = 2;
alert(blah());
or use a closure:
function bleh() {
var a;
function blah(){
a = 1
}
a = 2;
alert(blah());
}
or you could pass it around with a return (which behaves differently, but probably is what you want to do):
function blah(a){
a = 1
return a;
}
a = 2;
alert(blah(a));

Categories

Resources