javascript 中没有关键字 var 的范围 [英] scope in javascript without the keyword var
问题描述
function jjj(asi) {
asi=3;
}
jjj();
console.log(asi);
这里我认为 asi
是一个全局变量,但是在运行这段代码时,它给出了 asi
没有定义.
Here I am thinking that asi
is a global variable but while running this code it is giving that asi
is not defined.
根据书籍和官方文档,我研究过,如果你提到变量名而没有关键字 var 那么它就变成全局的,所以我认为同样的规则也适用于 asi 变量
As per the books and official doc I have studied that if you mention the variable name without the keyword var then it becomes global so I think same rule applies to asi variable also
推荐答案
这里我认为 asi 是一个全局变量,但是在运行此代码时,它给出了 asi 未定义
here I am thinking that asi is a global variable but while running this code it is giving that asi is not defined
它会创建一个隐式全局如果你没有将它声明为一个参数,例如:
It would be creating an implicit global if you weren't declaring it as a parameter instead, e.g.:
function jjj() {
// ^---------- removed `asi` here
asi = 3;
}
jjj();
console.log(asi);
请注意,隐式全局变量一个非常糟糕的主意(我称我的博客文章隐式全局变量的恐怖是有原因的),您应该使用严格模式 使他们成为他们一直应该出现的错误:
Note that implicit globals are a really bad idea (I called my blog post on them The Horror of Implicit Globals for a reason) and you should use strict mode to make them the errors they always should have been:
"use strict";
function jjj() {
asi = 3; // ReferenceError: asi is not defined
}
jjj();
console.log(asi);
这篇关于javascript 中没有关键字 var 的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!