No_name
No_name

Reputation: 2810

javascript callback function from different scope variable not defined

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.

Upvotes: 2

Views: 848

Answers (3)

Sibin Xavier
Sibin Xavier

Reputation: 306

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

Upvotes: 0

Jaromanda X
Jaromanda X

Reputation: 1

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

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68383

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

Upvotes: 1

Related Questions