JS 变量提升和var以及let

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>变量提升</title>
	</head>
	<body>
		<script type="text/javascript">
			// 使用var声明,会出现变量提升
			function foo() {
				var x = 'Hello, ' + y;
				console.log(x);
				var y = 'Bob';
			}
			foo();
			// 这里并不会报错,打印出来的数据是 hello,undefined;			// 因为js中会自动提升变量y的声明,但是不会提升变量y的赋值
			
			
			// 使用let
			function foo2() {
				let x = 'Hello, ' + y;
				console.log(x);
				let y = 'Bob';
			}
			//  使用let,会报错,y is not defined;
			
			
			// 另外,使用var声明变量,可以多次声明而不报错
			function foo3() {
				var x = 1;
				var x = 2;
				console.log(x);
			}
			foo3();
			// 使用let声明-这么做会报错,出现x has been declared	
			function foo5() {
				let x = 1;
				let x = 2;
				console.log(x);
			}
			foo5();
		</script>
	</body>
</html>

猜你喜欢

转载自blog.csdn.net/xvzhengyang/article/details/84639179