RichW
RichW

Reputation: 10942

Passing a variable to a function (scope problem)

I'm trying to pass the value of p to the alert function - unfortunately at the moment it just comes up as undefined. I think the problem is because when that function is called p doesn't exist anymore. How would I pass p to that function and make it retain the value?

function B(p,u) {
    var foo = {};
    foo[u] = function(p) {
        alert('visit internal page '+p);
    };
    $.router(foo);
}

B("about", "!/about");

Upvotes: 1

Views: 488

Answers (2)

gblazex
gblazex

Reputation: 50137

The problem is that you have two p variables at the same time.

function B(outer_p, u) { // <- first p
    var foo = {};
    foo[u] = function(inner_p) { // <- second p
        alert('visit internal page '+ outer_p); // depending on what 
    };                                          // you want to display here
    $.router(foo);
}

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630637

Just leave it off the parameter list, like this:

function B(p,u) {
    var foo = {};
    foo[u] = function() {
        alert('visit internal page '+p);
    };
    $.router(foo);
}

Currently you're specifying a parameter p on the inner function, and unless that's provided when it's called (doesn't seem it is) that more local p variable will be undefined. Instead just don't specify it as a parameter, and it'll use the p from the parent scope.

Upvotes: 3

Related Questions