Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在JavaScript中,未声明的变量赋值是在函数范围之外访问的?_Javascript_Variables_Scope - Fatal编程技术网

在JavaScript中,未声明的变量赋值是在函数范围之外访问的?

在JavaScript中,未声明的变量赋值是在函数范围之外访问的?,javascript,variables,scope,Javascript,Variables,Scope,通常,函数内部声明的变量(变量声明)只能由该函数及其内部函数访问。但是,函数内部未声明的变量赋值可以通过使其成为全局变量而在JavaScript中的函数范围之外访问。为什么会发生这种情况 var hello = function() { number = 45; }; hello(); console.log(number); // 45 is printed in the console 对未出现在var声明中的变量的赋值被视为对全局变量的赋值(全局上下文的属性)。在“严格”模式

通常,函数内部声明的变量(变量声明)只能由该函数及其内部函数访问。但是,函数内部未声明的变量赋值可以通过使其成为全局变量而在JavaScript中的函数范围之外访问。为什么会发生这种情况

var hello = function() {
   number = 45;
};
hello();
console.log(number);    // 45 is printed in the console

对未出现在
var
声明中的变量的赋值被视为对全局变量的赋值(全局上下文的属性)。在“严格”模式下,此类分配会引发错误

这就是JavaScript的工作原理。如果正确声明了
number
,则它将不会在全局可见:

var hello = function() {
   var number = 45;
}
hello();
console.log(number);    // undefined is printed in the console

对未出现在
var
声明中的变量的赋值被视为对全局变量的赋值(全局上下文的属性)。在“严格”模式下,此类分配会引发错误

这就是JavaScript的工作原理。如果正确声明了
number
,则它将不会在全局可见:

var hello = function() {
   var number = 45;
}
hello();
console.log(number);    // undefined is printed in the console

因为说明书上这么说


添加
“严格使用”编码到文件或函数的顶部以禁止此操作。

因为规范中有这样的说明

添加
“严格使用”到文件或函数的顶部,以禁止此操作