1

在 Javascript 中,据说函数是使用定义函数时有效的范围执行的。它与调用函数时的作用域无关。

它到底是什么意思?有人可以用简单的例子解释一下。

4

2 回答 2

2

下面的输出是 A 因为foo是在 的范围内定义的,所以它使用function a的变量也是在 的范围内定义的变量。datafunction a

即使在where范围内调用了该函数,它也不输出 B 。function bdata = "B"

<div id="output"></div>
<script>
  var data = "global";

  function a() {
    var data = "A";
    function foo() {
       document.getElementById('output').innerHTML = data;
    }
    return foo;
  }

  function b() {
    var data = "B";
    var func = a();
    func();
  }

  b();
</script>
于 2013-03-15T12:31:17.397 回答
0
// Global variables are on every scope chain
var global = 'global'

// Function variables are only on a function's scope chain
function bar() {
  var fn = 'fn';

  // foo called from here where fn is avaialble as a local variable
  foo(); // undefined

  return function() {
    alert(fn)
  }
}


function foo() {
  // foo can access global because it's on its scope chain
  alert(global);

  // Can't access fn because it's on bar's scope chain
  // so returns undefined
  alert(typeof fn);    
}

// the function returned by bar has access to fn
var f = bar(); // global

f(); // fn
于 2013-03-15T12:37:09.287 回答