简体   繁体   English

从嵌套函数内部访问IIFE变量

[英]Access IIFE variables from inside nested functions

I have an IIFE with a nested function inside. 我有一个带有嵌套函数的IIFE。 There is a word variable both inside and outside the nested function. 嵌套函数的内部和外部都有一个word变量。 How can I access the word variable outside the nested function instead of the inside one? 如何在嵌套函数外部而不是内部函数中访问word变量?

Code: 码:

 (function (){ let word = "Hello"; function sayHello(){ let word = "Greetings"; console.log(word + " Everyone!"); // This is using the inside word variable instead of the outside one. How can I specify JS to use the outside one instead? } sayHello(); })(); 

Pass the outer variable as a parameter so you can reference it separately from the inside variable: 将外部变量作为参数传递,以便您可以将其与内部变量分开引用:

 (function() { let word = "Hello"; function sayHello(outerWord) { let word = "Greetings"; console.log(outerWord + " Everyone!"); } sayHello(word); })(); 

Alternatively, simply give the variables different names, if you're allowed - shadowing is usually a bad idea for exactly this reason. 另外,如果允许的话,只需给变量取不同的名称-正是由于这个原因,阴影通常是个坏主意。

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

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