0%

JavaScript 基础

JavaScript 基础总结(变量提升、严格模式)


变量与函数提升规则

  • 变量提升:按顺序执行,变量声明提升但赋值不会提升。
  • 函数提升:整个函数体提升到全局作用域顶部。
  • 优先级:函数提升 > 变量提升。
1
2
3
4
5
6
7
console.log(a); // undefined
var a = 2;

foo(); // 正常调用
function foo() {
console.log("函数提升成功");
}

使用 use strict 严格模式

作用:

  • 避免创建意外的全局变量
  • 禁止使用未声明变量,防止内存泄漏;
  • this 默认绑定到 undefined 而非 window
1
2
3
4
5
6
7
function foo() {
"use strict";
console.log(this.a); // ❌ TypeError
}

var a = 2;
foo(); // 严格模式下 this 是 undefined,无法读取 this.a

1
2
3
4
5
6
7
8
9
10
(function() {
"use strict";
foo(); // 严格模式下调用函数则不影响默认绑定
})();

function foo() {
console.log(this.a);
}

var a = 2;
-------------本文结束感谢您的阅读-------------