ste*_*teo 3 javascript scope callback
我试图variable在一个function调用a的内部重新使用callback,但它不会像我认为的那样工作;
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我无法理解,如果这是关闭相关的问题,但一开始我预计,someval在callingfn将已经确定.
我哪里错了?
函数fn()不同于a()它fn作为参数接收.
你可以发送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);
}
}
Run Code Online (Sandbox Code Playgroud)
或者简单地声明var someval为全局范围,目前它位于使其成为本地的函数内.
希望这可以帮助.