例如,这是我们的代码:
function blabla(A,B) {
// Something
httpReq.onreadystatechange = function(A,B) {
if (httpReq.readyState == 4) {
// console.log(A,B) says 'undefined'
// How can I use the values of A and B here?
};
}
}发布于 2012-09-20 04:01:32
你只需要使用它们。你的问题是影子。内部函数参数会覆盖外部函数参数,因为它们具有相同的名称。
通常,任何局部变量都可用于同一作用域中声明的任何函数。这意味着你只需要使用它们,只要你不用同名的新局部变量来隐藏它们。
function blabla(a, b) {
// Something
httpReq.onreadystatechange = function(c, d) {
// logs undefined, because no arguments are actually passed in
// so the variables are undefined.
console.log(c, d);
// log arguments passed to blabla() because it picks up the reference
// the parent scope.
console.log(a, b);
}
}
blabla('Hi', 'There'); // should log "Hi", "There"只要您为每个函数的参数使用唯一的变量名,这就可以正常工作。
发布于 2012-09-20 04:00:13
只需使用A和B即可。闭包支持(纯粹的、JavaScript的基本特性)将会解决这个问题。请参阅How do JavaScript closures work?
在你的情况下,
function blabla(A,B) {
// Something
httpReq.onreadystatechange = function(paramA, paramB) {
if (httpReq.readyState == 4) {
// console.log(A,B) prints A and B arguments of blabla
// console.log(paramA, paramB) prints actual parameters
};
}
}发布于 2012-09-20 04:03:20
您可以将A和B临时存储在一个变量中。
var data = {};
function blabla(A,B) {
data.A = A;
data.B = B;
httpReq.onreadystatechange = function() {
// How can I lead the values of A and B into this?
console.log(data.A, data.B)
}
}https://stackoverflow.com/questions/12501959
复制相似问题