1

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

2 Answers 2

3

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.

3
  • Fantastic, that was easier than I expected! No idea why that works though, I'll have to do some research. Thanks for the answer!
    – RichW
    Nov 21, 2010 at 11:02
  • 1
    @RichW - any variables in the parent scope are available to use, any parameter on a function at any level however has to be specified, so when you have function(p) and just call it via foo[u](), it'll be undefined...since you didn't pass any parameters, but by leaving it off the only p it can possibly use is the one in the parent scope...does that make any more sense? Nov 21, 2010 at 11:08
  • Makes perfect sense now, thanks Nick! Unfortunately it's one of those problems that seems difficult to research on Google as you don't know what to type in!
    – RichW
    Nov 21, 2010 at 11:12
1

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);
}
2
  • I was hoping the value of p would inherit through the functions (guess it doesn't work like that!). Thanks for the info!
    – RichW
    Nov 21, 2010 at 11:03
  • What do you mean by inherit? Outer p is available in your inner function. But if you declare p in the inner function parameter list, it will be assigned undefined by default and will cover/hide the outer p because of name collision.
    – gblazex
    Nov 21, 2010 at 11:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.