<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>JavaScript變量提升 面試題</title>
</head>
<body>
<script type="text/javascript">
//函數提示優於變量
console.log(a);//function a(){}
console.log(b);//undefined
var a = 1; function a(){} var b= function(){}; console.log(a)//1
</script>
</body>
</html>
面試題2:
var a = 10; (function () { console.log(a) a = 5 console.log(window.a) var a = 20; console.log(a) })()
解釋:
執行解析步驟: var a = undefined; a = 10; (function () { // 變量提升(預解析)
var a = undefined; console.log(a); // 輸出undefined
a = 5; console.log(window.a); // 找window(全局)對象的a, 輸出10
a = 20; console.log(a); // 輸出20
})()
