JS中的全局范围到底是什么?

时间:2020-05-13 09:23:41

标签: javascript function

我正在从以下链接中了解有关JavaScript中的Function()构造函数的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function

它提到以下事实:

使用Function构造函数创建的函数不会创建其创建上下文的闭包。它们总是在全局范围中创建。运行它们时,它们将只能访问自己的局部变量和全局变量,而不能访问创建Function构造函数的作用域中的那些变量

let count = 0; // var count = 0 works!

function makeCounter() {
  let count = 0;

  return new Function('return count++;');

}

let counter = makeCounter();

console.log( counter() ); // "ReferenceError: count is not defined 

在上面的示例中,语句let count = 0是否在全局范围内的功能makeCounter()上方?

我尝试阅读有关范围界定的工作原理,并发现了Any variable declared outside of a function belongs to the global scope, and is therefore accessible from anywhere in your code

此处:https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/

结果let count = 0符合全局范围的定义,但仍然给出错误!

编辑:我了解范围定义的工作原理,更关心Function()的工作原理,因为它按照定义中的定义从global scope访问变量。

1 个答案:

答案 0 :(得分:0)

要回答标题中的问题:“ JS中的全局范围到底是什么? “

这取决于javaScript的运行位置。

传统上,它表示作用域的最外层“窗口对象”,功能和对象形式的闭包是作用域的内部级别(作用域约束变量)。

作用域就像html元素的嵌套。

let count = 0; // we only use "let" the first time we declar a variable

function makeCounter() { 
  let count = 0; // okay, so this `count` is completely different than the first one
}
function makeCounter( count ) { // and it will even get more confusing of we try to pass a variable to the funtion
  count = 0; 
}

这可能有帮助吗?

let count = 0; // we only use "let" the first time we declar a variable

function makeCounter( current_count ) {
  return current_count++;
}

for ( let i = 0; i < 10; i++ ) {
  count = counter( count );
  console.log( count );
}