Javascript函数执行范围

时间:2013-03-15 12:26:51

标签: javascript function

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

究竟是什么意思?有人可以用简单的例子来解释。

2 个答案:

答案 0 :(得分:2)

以下输出为A,因为在foo范围内function a 已定义,因此它使用的变量data是也在function a

的范围内定义

即使该函数在function b data = "B"范围内被称为,它也不会输出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>

答案 1 :(得分: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