JavaScript核心概念
外观
JavaScript核心概念[编辑 | 编辑源代码]
JavaScript核心概念是前端开发中的基础构建块,涵盖语言的基本特性、运行机制及关键编程范式。理解这些概念对于编写高效、可维护的代码至关重要。
变量与作用域[编辑 | 编辑源代码]
JavaScript中的变量声明方式(var
, let
, const
)决定了其作用域和提升行为:
// 示例:变量作用域对比
function scopeExample() {
if (true) {
var functionScoped = "I'm function-scoped";
let blockScoped = "I'm block-scoped";
}
console.log(functionScoped); // 输出: I'm function-scoped
console.log(blockScoped); // 抛出ReferenceError
}
类型 | 作用域 | 可重复声明 | 暂时性死区 |
---|---|---|---|
var |
函数作用域 | 允许 | 无 |
let |
块级作用域 | 禁止 | 存在 |
const |
块级作用域 | 禁止 | 存在 |
数据类型[编辑 | 编辑源代码]
JavaScript是动态类型语言,包含7种原始类型和1种引用类型:
- 原始类型:
String
,Number
,BigInt
,Boolean
,Symbol
,Null
,Undefined
- 引用类型:
Object
(包含Array
,Function
等)
类型转换示例:
// 显式类型转换
let num = Number("42"); // 字符串转数字
let str = String(42); // 数字转字符串
// 隐式类型转换
console.log("5" + 3); // 输出: "53" (字符串拼接)
console.log("5" - 3); // 输出: 2 (数学运算)
函数与闭包[编辑 | 编辑源代码]
JavaScript函数是一等公民,支持高阶函数和闭包特性:
// 闭包示例
function createCounter() {
let count = 0;
return function() {
return ++count;
};
}
const counter = createCounter();
console.log(counter()); // 输出: 1
console.log(counter()); // 输出: 2
闭包的内存模型:
原型与继承[编辑 | 编辑源代码]
JavaScript采用原型继承机制,每个对象都有__proto__
属性指向其原型:
// 原型链示例
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return `Hello, ${this.name}!`;
};
const john = new Person("John");
console.log(john.greet()); // 输出: Hello, John!
原型链图示:
异步编程[编辑 | 编辑源代码]
JavaScript通过事件循环处理异步操作,主要模式包括:
1. 回调函数
setTimeout(() => {
console.log("Delayed execution");
}, 1000);
2. Promise
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
3. async/await
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
事件循环模型:
实际应用案例[编辑 | 编辑源代码]
购物车计算功能展示多个核心概念的综合运用:
// 使用闭包管理私有变量
function createCart() {
let items = [];
return {
addItem: function(product, price) {
items.push({ product, price });
},
calculateTotal: function() {
return items.reduce((total, item) => total + item.price, 0);
},
applyDiscount: async function(discountCode) {
try {
const isValid = await validateDiscount(discountCode);
if (isValid) return this.calculateTotal() * 0.9;
return this.calculateTotal();
} catch {
return this.calculateTotal();
}
}
};
}
// 使用示例
const cart = createCart();
cart.addItem("Laptop", 999);
cart.addItem("Mouse", 25);
console.log(cart.calculateTotal()); // 输出: 1024
高级概念[编辑 | 编辑源代码]
对于进阶开发者,需要理解以下机制:
- 执行上下文:包含变量对象、作用域链和this绑定
- 内存管理:引用计数与标记清除垃圾回收
- 模块系统:ES Modules与CommonJS对比
内存回收示例:
数学计算[编辑 | 编辑源代码]
JavaScript数值计算遵循IEEE 754标准,注意精度问题:
使用Number.EPSILON
比较浮点数:
function floatEqual(a, b) {
return Math.abs(a - b) < Number.EPSILON;
}
通过系统化学习这些核心概念,开发者可以建立坚实的JavaScript基础,为进阶框架学习和复杂应用开发做好准备。