字符串引用在javascript闭包中表现奇怪

时间:2014-03-27 06:56:39

标签: javascript closures

我希望以下代码可以打印“cat”,而是打印“bat”

var a = "cat";
x = function(){
  var b = a;
  console.log(b);
}
a = "bat";
x();

我能做些什么来获得 内部功能以我想要的方式工作?有没有办法在不分配任何空间的情况下做到这一点?

3 个答案:

答案 0 :(得分:1)

这是因为在执行函数x之前,变量a被重新赋值为“cat”。因此,在调用x()之前,变量b将是未声明的。在声明发生期间,a的值是“bat”。

答案 1 :(得分:0)

在此下面的代码段

x = function(){
  var b = a;
  console.log(b);
}

您刚刚定义了一个匿名函数,该函数绑定外部分数变量a,从而生成a closure。所以它与其外部范围有关。所以在执行x的功能时

x();

全局范围内的值为"bat",导致函数返回"bat"

这可能会更清楚

var a = "cat";
x = function(){
  var b = a;
  alert(b);
}
a = "bat";
x();//alerts bat
a = "wow";
x();//alerts wow
a = "im bound to the outer scope";
x();//alerts im bound to the outer scope

答案 2 :(得分:0)

这解决了我遇到的问题:

var a = "cat";
function copyCatBuilder(animal){
    return function(){ console.log(animal)};
}
x = copyCatBuilder(a);
a = "bat";

x();

程序现在输出“cat”