[英]Javascript: variable scope in callback
I'm trying to re-use variable
inside a function
that calls a callback
, but it does not work the way I think it should; 我试图在一个调用callback
的function
中重用variable
,但它不像我认为的那样工作;
another()(); //=> logs "somevalue"
callingfn(); //=> logs " someval is not defined"
function a(fn){
var someval = "some-value";
return fn();
}
function callingfn(){
return a.call(this, function(){
console.log(someval)
})
}
function another(){
var sv = "somevalue";
return function(){
console.log(sv);
}
}
I'm not able to understand if this is closure-related problem, but at first I expected that someval
in callingfn
would have been defined. 我无法理解这是否与闭包相关的问题,但起初我预计在someval
中的callingfn
将被定义。
Where am I wrong? 我哪里错了?
function fn()
is different from a()
though it receives fn
as parameter. 函数fn()
与a()
不同,但它接收fn
作为参数。
You could possibly send someval
as parameter. 您可以发送someval
作为参数。
another()(); //=> logs "somevalue"
callingfn(); //=> logs " someval is not defined"
function a(fn){
var someval = "some-value";
return fn(someval);
}
function callingfn(){
return a.call(this, function(someval){
console.log(someval)
})
}
function another(){
var sv = "somevalue";
return function(){
console.log(sv);
}
}
Or simply declare the var someval
as global scope, currently it is inside a function which makes it local. 或者简单地将var someval
声明为全局范围,目前它位于使其成为局部的函数内。
Hope this helps. 希望这可以帮助。
Try This: 尝试这个:
another()(); //=> logs "somevalue"
callingfn(); //=> logs " someval is not defined"
var someval;
var sv;
function a(fn){
someval = "some-value";
return fn();
}
function callingfn(){
return a.call(this, function(){
console.log(someval)
})
}
function another(){
sv = "somevalue";
return function(){
console.log(sv);
}
}
Define someval
outside the scope of the functions: 在函数范围之外定义someval
:
var someval; // <- outside of the scope of any one function
another()(); //=> logs "somevalue"
callingfn(); //=> logs " someval is not defined"
function a(fn){
someval = "some-value"; // <-remove "var" to access the variable outside the scope
return fn();
}
function callingfn(){
return a.call(this, function(){
console.log(someval)
})
}
function another(){
var sv = "somevalue";
return function(){
console.log(sv);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.