js中的var定义局部变量

本文详细解析了JavaScript中作用域的概念,包括局部变量和全局变量的定义、使用及注意事项,强调了避免在局部作用域使用全局变量的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

摘自《O'Reilly - Learning JavaScript》

 

When you use var with a variable, you’re defining the variable with local scope, which means you can access them only within the function in which you’ve defined them. If I didn’t use var, the variable msg would be global and would have scope inside and outside the function.

Using a global variable in a local context isn’t a bad thing—and it may be necessary at

times—but it isn’t a good practice, and you should avoid it if possible.

 

Here are the rules regarding scope:

• If you declare a variable with the var keyword in a function or block of code, its

use is local to that function.

• If you use a variable without declaring it with the var keyword, and a global variable

of the same name exists, the local variable is assumed to be the already existing

global variable.

• If you declare a variable locally with a var keyword, but you do not initialize it (i.e.,

assign it a value), it is local and accessible but not defined.

• If you declare a variable locally without the var keyword, or explicitly declare it

globally but do not initialize it, it is accessible globally, but again, it is not defined.

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值