[英]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.为了避免全局变量,您需要在每个变量名称之前添加
var
、 const
或let
。 If you omit these keywords the variable begin global.如果省略这些关键字,则变量开始为全局变量。 In your case q is global
在你的情况下 q 是全球性的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.