问题
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