[英]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 . 我试图将p的值传递给alert函数 - 不幸的是,它刚刚出现为未定义的 。 I think the problem is because when that function is called p doesn't exist anymore.
我认为问题是因为当调用该函数时, p不再存在。 How would I pass p to that function and make it retain the value?
如何将p传递给该函数并使其保留该值?
function B(p,u) {
var foo = {};
foo[u] = function(p) {
alert('visit internal page '+p);
};
$.router(foo);
}
B("about", "!/about");
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
. 目前你在内部函数上指定了一个参数
p
,除非在调用它时(似乎不是这样)提供了更多本地p
变量将是undefined
。 Instead just don't specify it as a parameter, and it'll use the p
from the parent scope. 相反,只是不要将其指定为参数,它将使用父作用域中的
p
。
The problem is that you have two p
variables at the same time. 问题是你有两个
p
变量同时。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.