从函数中获取对局部作用域的引用

时间:2017-01-15 23:27:54

标签: javascript scope

假设我有这段代码:

// somewhere else
var outFn = (() => {
  var local = 5;
  var fn = () => { console.log(local); };
  return fn;
})();

// I have a reference to outFn
outFn(); // prints 5

如何引用outFn的本地范围,即如何使用我对local的引用来获取对outFn变量的引用?

1 个答案:

答案 0 :(得分:0)

不要写下最后一个括号:

var outFn = (() => {
  var local = 5;
  var fn = () => { console.log(local); };
  return fn;
}) //(); <-- No need those parentheses 

然后:

  var localFn= outFn(); 
  localFn() ; // prints 5

如果您还想同时访问local变量,请将其附加到fn,如下所示:

var outFn = (() => {
  var fn = () => { console.log(fn.local); };
  fn.local = 5;
  return fn;
}); 

现在您可以阅读local

  var localFn= outFn(); 
  localFn.local ; // ===5