关键字: var,function ,let, 全局作用域(window),变量提升
直接先来3道题,如果都会,本篇文章可以直接pass
-
console.log(a); var a = 12; a = 14; console.log(a);
-
console.log(a); let a = 12; console.log(a);
-
var a = 12; console.log(a); console.log(window.a);
-
console.log(sum(1,2)); function sum(n,m){ return n+m; }
-
console.log(sum(1,2)); var sum = function(n,m) { return n+m; } console.log(sum(1,2));
看完这些题你的答案是什么?里面涉及的知识点有哪些?
-
答案
- undefined 14
- 报错
- 12 12
- 3
- 报错
知识点
- var 和function会存在变量提升, 区别是 var只是提前声明没有提前赋值; 而function会提前声明并且赋值,也就是让这个函数提前定义。但是使用”函数表达式的形式不会发生提前定义的情况“
- 在全局作用域下使用var声明,例如var b = 12; 相当于window.a = 12;
- 代码执行报错了,不会再向下执行了!!!!!答题时切记!!