JavaScript 中的提升:一个可能欺骗你的简单概念
提升是 JavaScript 面试中最常见的问题之一,通常被认为是适合初学者的概念。然而,它的行为可能具有欺骗性,甚至会让经验丰富的开发人员陷入陷阱。
什么是提升?
JavaScript 中的提升是一种行为,在代码执行之前,在编译阶段将变量和函数声明移动到其包含范围(脚本或函数)的顶部。
仅提升声明,而不提升初始化或赋值。
提升对于变量、函数和类有不同的行为。让我们一一了解它们。
变量提升
var 关键字的提升
console.log(a); // Output: undefined (declaration hoisted, not initialisation) var a = 5; console.log(a); // Output: 5
let 和 const 关键字的提升
console.log(b); // ReferenceError: Cannot access 'b' before initialisation console.log(c); // ReferenceError: Cannot access 'c' before initialisation let b = 10; const c = 'alphabet';
函数提升
greet(); // Output: Hello! function greet() { console.log("Hello!"); }
sayHello(); // TypeError: sayHello is not a function var sayHello = function() { console.log("Hello!"); };
类提升
const obj = new MyClass(); // ReferenceError: Cannot access 'MyClass' before initialisation class MyClass { constructor() { console.log("Hello from MyClass!"); } }
值得记住
一些值得遵循的最佳实践
额外信息
什么是暂时死区(TDZ)?
TDZ 为什么存在?
提升可能看起来像一个简单的概念,但它的细微差别甚至会让经验丰富的开发人员措手不及。通过了解声明在后台的处理方式,您可以编写更干净、更可预测的代码,并解决那些棘手的面试问题。请记住,掌握基础知识是成为 JavaScript 专业人士的第一步!祝您编码愉快!