Javascript函数的执行范围

Javascript function execution scope

本文关键字:范围 执行 函数 Javascript      更新时间:2023-09-26

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

这到底是什么意思?谁能举个简单的例子解释一下?

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

它不输出B,即使函数function b的范围内被称为,其中data = "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>
// 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