繁体   English   中英

Javascript函数执行范围

[英]Javascript function execution scope

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

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

以下内容的输出为A,因为foo是在function a的范围内定义 function a ,因此它使用的变量data也是在function a的范围内定义的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>
// 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM