假设我有这段代码:
// 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
变量的引用?
答案 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