JohnW
JohnW

Reputation: 345

Accessing a variable from outside its scope?

So, I'm relatively new to javascript, and still having trouble getting my head round variable scope. So, what I'm trying to do is access a variable from outside a function (all within the same object).

See below:

function GameCard(imageSource, div)
{
    this.cardImage = new Image();
    this.cardImage.src = imageSource;

    this.imageString = "<img src='" + this.cardImage.src + "' />";

    this.hiddenImage = new Image();
    this.hiddenImage.src = HIDDEN_SOURCE;

    this.clicked = false;

    this.cardDiv = div;

    $(this.cardDiv).click(function() {
        alert(this.imageString);
        $(this).flip({
            direction:'lr',
        });
    });
}

The alert (my unfortunate debugging) is saying imageString is undefined within the click handler function. Which makes sense, how would I access it?

Thanks in advance, J

Upvotes: 0

Views: 1318

Answers (3)

Pointy
Pointy

Reputation: 413826

Two ways: first, you can stash this in another variable:

var saveThis = this;

before setting up the "click" handler, and then use "saveThis" in the handler code:

$(this.cardDiv).click(function() {
    alert(saveThis.imageString);
    $(saveThis).flip({
        direction:'lr',
    });
});

Second way: bind the handler function to the object you want:

$(this.cardDiv).click(function() {
    alert(this.imageString);
    $(this).flip({
        direction:'lr',
    });
}.bind(this));

That second way requires a shim in older IE versions.

Upvotes: 2

griegs
griegs

Reputation: 22760

In this case "this" refers to $(this.cardDiv) and not the parent object.

You might consider having a javascript object containing all the data outside of your CardGame object

That way the data will be scoped higher up and accessible from within your method

Upvotes: 1

Moby&#39;s Stunt Double
Moby&#39;s Stunt Double

Reputation: 2550

Declare a var of imageString outside of the function and use it in both GameCard and the anonymous click() event's function.

The two functions don't share memory spaces, as the anonymous function is not executed in the context of GameCard, but they both share the global variables declared outside.

Upvotes: 1

Related Questions