博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaScript中的全局变量介绍
阅读量:2518 次
发布时间:2019-05-11

本文共 1662 字,大约阅读时间需要 5 分钟。

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 . 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; // globalfunction 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:

参考文献:

()

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

翻译自:

转载地址:http://elrwd.baihongyu.com/

你可能感兴趣的文章
HDU 1829/POJ 2492 A Bug's Life
查看>>
CKplayer:视频推荐和分享插件设置
查看>>
CentOS系统将UTC时间修改为CST时间
查看>>
redis常见面试题
查看>>
导航控制器的出栈
查看>>
玩转CSS3,嗨翻WEB前端,CSS3伪类元素详解/深入浅出[原创][5+3时代]
查看>>
iOS 9音频应用播放音频之播放控制暂停停止前进后退的设置
查看>>
Delphi消息小记
查看>>
JVM介绍
查看>>
将PHP数组输出为HTML表格
查看>>
经典排序算法回顾:选择排序,快速排序
查看>>
BZOJ2213 [Poi2011]Difference 【乱搞】
查看>>
一道关于员工与部门查询的SQL笔试题
查看>>
Canvas基础
查看>>
[Hive - LanguageManual] Alter Table/Partition/Column
查看>>
可持久化数组
查看>>
去除IDEA报黄色/灰色的重复代码的下划波浪线
查看>>
Linux发送qq、网易邮件服务配置
查看>>
几道面试题
查看>>
【转】使用 WebGL 进行 3D 开发,第 1 部分: WebGL 简介
查看>>