JavaScript has no block scope

本文深入探讨了JavaScript中变量作用域的概念,对比了与C等其他语言的差异,并强调了在函数中声明变量的最佳实践。通过具体示例展示了在函数内部声明的变量如何在不同上下文中被访问,以及在不同作用域内使用变量的重要性。

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

JavaScript's Syntax comes from C, In all other C-like languages, a block(a set of statements wrapped in  curly braces) creates a scope.

Variables declared in a block are not visible outside of the block. JavaScript uses the block syntax, but does not provide block scope: a variable

declared in a block is visible everywhere in the function containing the block. This  can be surprising to programmers with experience in other

languages.

In most languages, it is generally best to declare variables at the site of first use. That turns out to be a bad practice in JavaScript because

it does not have block scope. It's better to declare all variables at the top of each function.

</pre><pre name="code" class="javascript"><script>
		var testFunc = function(o) {
			var i = 4;
			
			document.writeln('<br/>value of g= ' + g);
			//document.writeln('<br/>value of j= ' + j);
			
			if (typeof o === 'string') {
				var k;
				for (k = 0; k < i; k++) {
					var g = k + i;
				}
			}
			
			document.writeln('<br/>value of i= ' + i);
			document.writeln('<br/>value of k= ' + k);
			document.writeln('<br/>value of g= ' + g);
		}
		
		testFunc('hello, world');
	</script>
	
输出结果:

value of g= undefined 
value of i= 4 
value of k= 4 
value of g= 7

变量 g定义在在 for 循环块里,而k 定义在if块中,在C和Java看来,再for,if块外是不能再引用g和k的,而JavaScript则可以,因为他没block scope的概念,只要在

function里定义了,就可以在任何地方引用。这里,当还没有定义变量g时,确使用了 它“

document.writeln('<br/>value of g= ' + g);结果为 undefined,这是因为,当函数开始时会扫描整个function block, 为里面的每一个变量赋予初始值undefined.
而"<span style="font-family: Arial, Helvetica, sans-serif;">//document.writeln('<br/>value of j= ' + j);"则会编译失败,因为j was not defined anywhere.</span>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值