Javascript:回调函数中的变量作用域

3

我试图在调用回调函数函数内重新使用变量,但它并不像我想象的那样工作;

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

我无法确定这是否与闭包有关,但最初我期望在 callingfn 中的 someval 已被定义。

我错在哪里了?


someval 是局部变量,属于函数 a() 的作用域,只能在 a() 函数内及其内部的闭包中访问(在您发布的代码中没有闭包)。 - techfoobar
嗯,对的。我在想是否有办法将回调函数作为闭包放到 a() 中。 - steo
这是不可能的,因为要成为回调函数,它必须在 a() 内部定义。 - techfoobar
3个回答

6

fn()函数与传入它作为参数的a()函数不同。

你可能会将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);
  }
}

或者直接将var someval声明为全局范围,目前它在函数内部使其成为局部变量。

希望这可以帮助到您。


1

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

1

在函数的范围之外定义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);
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接