在javascript中从外部函数访问内部变量 [英] Access inner variables from external functions in javascript

查看:649
本文介绍了在javascript中从外部函数访问内部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从外部函数访问内部变量,如此示例?

Is it possible to access an inner variable from an external function like this example?

function a(f) {
  var c = 'test';
  f();
}

a(function() {
  alert(c);  //at this point, c should = "test"
});


推荐答案

不,这不行。重要的是(词汇上)一个函数定义,而不是调用的地方。

No, that won't work. What matters is where (lexically) a function is defined, not where it's invoked.

当弄清楚什么是(如果有的话)c指的是,语言在本地范围内查找,然后在下一个范围中基于函数的定义。因此,如果在的另一个函数中调用a, 具有自己的本地c,则该值将是警报显示的内容。

When figuring out what (if anything) "c" refers to, the language looks in the local scope, then in the next scope out based on the definition of the function. Thus if that invocation of "a" took place in another function that did have its own local "c", then that value would be what the alert showed.

function b() {
  var c = 'banana';
  a(function() {
    alert(c);  
  });
}

b(); // alert will show "banana"

这篇关于在javascript中从外部函数访问内部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆