JavaScript中的全局变量介绍

Global variables are declared outside of a function for accessibility throughout the program, while local variables are stored within a function using var for use only within that function’s scope. If you declare a variable without using var, even if it’s inside a function, it will still be seen as global:

全局变量在函数外部声明,以在整个程序中进行访问,而局部变量使用var存储在函数中,仅在该函数的范围内使用 。 如果在不使用var情况下声明变量,即使该变量位于函数内部,则仍将其视为全局变量:

var x = 5; // global

function someThing(y) {
  var z = x + y;
  console.log(z);
}

function someThing(y) {
  x = 5; // still global!
  var z = x + y;
  console.log(z);
}


function someThing(y) {
  var x = 5; // local
  var z = x + y;
  console.log(z);
}

A global variable is also an object of the current scope, such as the browser window:

全局变量也是当前作用域的对象,例如浏览器窗口:

var dog = “Fluffy”;
console.log(dog); // Fluffy;

var dog = “Fluffy”;
console.log(window.dog); // Fluffy

It’s a best practice to minimize global variables. Since the variable can be accessed anywhere in the program, they can cause strange behavior.

最佳做法是最小化全局变量。 由于可以在程序中的任何位置访问变量,因此它们可能导致奇怪的行为。

References:

参考文献:

javascript中的全局变量和window.variable有什么区别? (What’s the difference between a global var and a window.variable in javascript?)

The scope of JavaScript variables are either global or local. Global variables are declared OUTSIDE the function and its value is accessible/changeable throughout the program.

JavaScript变量的范围是全局或局部。 全局变量在函数之外声明,并且其值在整个程序中都可以访问/更改。

You should ALWAYS use var to declare your variables (to make locally) else it will install GLOBALLY

您应该始终使用var声明变量(在本地生成),否则它将全局安装

Take care with the global variables because they are risky. Most of the time you should use closures to declare your variables. Example:

请注意全局变量,因为它们具有风险。 大多数时候,您应该使用闭包来声明变量。 例:

(function(){
  var myVar = true;
})();

更多信息: (More Information:)

翻译自: https://www.freecodecamp.org/news/global-variables-in-javascript-explained/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值