简体   繁体   English

访问自执行匿名函数中的变量

[英]Accessing variables inside Self-Executing Anonymous Function

as per my knowledge variables inside Self-Executing Anonymous Function are not accessible from outside but how come var q is accessible outside and why not var p then根据我的知识,自执行匿名函数中的变量无法从外部访问,但是为什么 var q可以在外部访问,为什么不能访问 var p那么

(function(){ 
    var p = q = 20;
})()
alert(q) --> 10
alert(p) --> p is undefined is the result im getting,

Variables defined within a anonymous function will not be accessible outside.匿名函数中定义的变量在外部无法访问。 However in your example you are setting variable p as a scoped variable & q as a global variable.但是,在您的示例中,您将变量p设置为作用域变量 & q作为全局变量。 The correct way you are looking for here would be:您在这里寻找的正确方法是:

var p;
var q;
p = q = 20;

To avoid global variable you need to add var , const or let before each variable name.为了避免全局变量,您需要在每个变量名称之前添加varconstlet If you omit these keywords the variable begin global.如果省略这些关键字,则变量开始为全局变量。 In your case q is global在你的情况下 q 是全球性的

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

相关问题 如何在自执行匿名函数内调用函数? - how to call a function inside a self-executing anonymous function? 访问自执行功能 - Accessing a self-executing function 在自执行匿名函数中使用undefined - Using undefined in self-executing anonymous function 添加自执行匿名函数以在访问$时扩展AngularJS中的Sir Trevor - Adding a Self-Executing Anonymous Function to extend Sir Trevor in AngularJS whilst accessing $ 访问匿名自执行函数的参数时,为什么需要使用“ this”关键字? - Why do I need to use the “this” keyword when accessing a parameter for an anonymous self-executing function? 从内部自动执行的匿名成员函数访问父原型作用域 - Access parent prototype scope from inside self-executing anonymous member function 匿名自执行js函数内部的全局变量在外部仍然可用? - Global variable inside anonymous self-executing js function still available outside? 为什么Closure Compiler不识别自执行匿名函数中的类型声明? - Why doesn't Closure Compiler recognize type declarations inside a self-executing anonymous function? 在显示模块模式中使用自执行匿名函数 - Using self-executing anonymous functions inside the revealing module pattern 如何访问自执行匿名函数中的对象变量 - How to access object variable inside self-executing anonymous functions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM