scope in javascript without the keyword var

随声附和 提交于 2021-01-01 14:03:55

问题


function jjj(asi) {
  asi=3;
}

jjj();
console.log(asi);

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

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


回答1:


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);



回答2:


In your case the function argument is reassigned with a new value.

function jjj(asi) {
  asi = 3 // the function argument will have new value
  mno = 4 // this will be a global variable
}
jjj();
console.log(asi);
console.log(mno);


来源:https://stackoverflow.com/questions/49022581/scope-in-javascript-without-the-keyword-var

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!