javascript - 没有关键字 var 的 JavaScript 作用域

标签 javascript scope

function jjj(asi) {
  asi=3;
}

jjj();
console.log(asi);

在这里,我认为 asi 是一个全局变量,但在运行此代码时,它给出了 asi 未定义。

根据书籍和官方文档,我研究过,如果您在没有关键字 var 的情况下提到变量名称,那么它就会成为全局变量,所以我认为同样的规则也适用于 asi 变量

最佳答案

here I am thinking that asi is a global variable but while running this code it is giving that asi is not defined

如果您没有将其声明为参数,则会创建一个隐式全局变量,例如:

function jjj() {
//           ^---------- removed `asi` here
  asi = 3;
}
jjj();
console.log(asi);

请注意,隐式全局变量是一个非常糟糕的主意(出于某种原因,我将关于它们的博客文章称为 The Horror of Implicit Globals ),您应该使用 strict mode让他们犯下他们本来应该犯的错误:

"use strict";
function jjj() {
  asi = 3; // ReferenceError: asi is not defined
}
jjj();
console.log(asi);

关于javascript - 没有关键字 var 的 JavaScript 作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49022581/

相关文章:

javascript - 是否有类似可选链的东西在 javascript 中进行赋值

javascript - 如果禁用了JavaScript,则为备用行为

javascript - 为什么我的 html 表单没有通过 ajax 将值返回到views.py?

Python:为什么描述符不能是实例变量?

javascript - 当对象非常多并且我试图在范围内访问它时,为什么我会得到 "Can not read property 0 of undefined"?

javascript - JSDoc 3.3.3 ES6 模板字符串刻度线上出现意外标记 ILLEGAL

javascript - 如何在不使用 ID 的情况下在 ul 中定位 li?

c - 将变量传递给函数 : scope and when to use & and *?

javascript - 是否有在条件(if)结构的条件语句中定义变量的有效方法?

javascript - 闭包中变量的性能与函数参数