一、基础语法
var
:函数作用域,存在变量提升(初始化为 undefined
)。
let
/ const
:块级作用域,无变量提升,const
声明的常量不可重新赋值(但引用类型可修改属性)。
var a = 10;
let b = 20;
const c = 30;
原始类型:Number
、String
、Boolean
、Null
、Undefined
、Symbol
、BigInt
。
引用类型:Object
(包括数组、函数、日期等)。
let str = "Hello"; // String
let num = 123; // Number
let arr = [1, 2, 3]; // Array
let obj = { name: "John" }; // Object
typeof
:检测原始类型。
Array.isArray()
:检测是否为数组。
Object.prototype.toString.call()
:精确检测类型。
typeof 123; // "number"
Array.isArray([ ]); // true
Object.prototype.toString.call(null); // "[object Null]"
显式转换:Number()
、String()
、Boolean()
。
隐式转换:避免使用!如 "5" + 2
→ "52"
,"5" - 2
→ 3
。
Number("123"); // 123
String(true); // "true"
条件语句:if...else
、switch
。
循环语句:for
、while
、for...of
(遍历可迭代对象)、for...in
(遍历对象属性)。
if (x > 0) {
console.log("正数");
} else {
console.log("非正数");
}
for (let i = 0; i < 5; i++) {
console.log(i);
}
函数声明:
function sum(a, b) {
return a + b;
}
函数表达式:
const sum = function(a, b) {
return a + b;
};
箭头函数(ES6):
const sum = (a, b) => a + b;
全局作用域:在函数外部声明的变量。
函数作用域:var
声明的变量。
块级作用域:let
/ const
声明的变量(如 if
、for
代码块内)。
定义:内部函数可以访问外部函数的变量(即使外部函数已执行完毕)。
用途:数据封装、私有变量、模块化开发。
function createCounter() {
let count = 0;
return {
increment: () => ++count,
getCount: () => count
};
}
const counter = createCounter();
counter.increment(); // count = 1
this
的绑定默认绑定:指向全局对象(严格模式下为 undefined
)。
隐式绑定:由调用位置的对象决定。
显式绑定:call()
、apply()
、bind()
。
const obj = {
name: "John",
greet: function() {
console.log(`Hello, ${this.name}`);
}
};
obj.greet(); // Hello, John
对象字面量:
const person = {
name: "Alice",
age: 25
};
构造函数:
function Person(name, age) {
this.name = name;
this.age = age;
}
const p = new Person("Bob", 30);
所有对象都有 prototype
,通过原型链实现继承。
function Animal() {}
Animal.prototype.speak = function() {
console.log("Animal speaks");
};
function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
const dog = new Dog();
dog.speak(); // Animal speaks
类声明:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} speaks`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
}
同步:代码按顺序执行,阻塞后续代码。
异步:代码放入任务队列,主线程空闲时执行。
console.log("Start");
setTimeout(() => console.log("Middle"), 0);
console.log("End");
// 输出顺序:Start → End → Middle
异步操作完成后执行的函数。
fetchData((data) => {
console.log("Data received:", data);
});
表示异步操作的最终完成或失败。
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
async/await
更简洁的异步代码写法。
async function getData() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
快速提取对象或数组的值。
const [a, b] = [1, 2]; // a=1, b=2
const { name, age } = { name: "John", age: 30 }; // name="John", age=30
使用反引号(`
)拼接字符串。
const name = "Alice";
const greeting = `Hello, ${name}!`; // Hello, Alice!
ES6 模块:
// math.js
export function add(a, b) {
return a + b;
}
// main.js
import { add } from "./math.js";
console.log(add(2, 3)); // 5
Set
:存储唯一值的集合。
Map
:键值对的集合(键可以是任何类型)。
const set = new Set([1, 2, 3]);
const map = new Map([[1, "one"], [2, "two"]]);
获取元素:
const element = document.getElementById("id");
const elements = document.querySelectorAll(".class");
修改内容:
element.textContent = "New Text";
element.innerHTML = "Bold Text";
添加事件监听器:
element.addEventListener("click", (event) => {
console.log("Button clicked!");
});
window
:浏览器窗口对象。
location
:控制页面地址。
navigator
:浏览器信息。
window.open("https://example.com"); // 打开新窗口
window.location.href = "https://example.com"; // 跳转页面
var
声明的变量会被提升到作用域顶部,但赋值不会。
console.log(a); // undefined
var a = 10;
使用 "use strict"
启用严格模式,防止隐式全局变量等错误。
"use strict";
x = 10; // 报错:x 未声明
常见原因:未清理闭包、未移除事件监听器。
解决方案:及时释放不再使用的资源。
使用 try...catch
捕获异常。
try {
riskyOperation();
} catch (error) {
console.error("An error occurred:", error);
}
箭头函数:简化函数写法,this
绑定外层作用域。
模板字符串:支持多行字符串和变量插值。
解构赋值:快速提取对象或数组的值。
类(Class):面向对象编程的语法糖。
模块化:import
/ export
替代 CommonJS。
Promise:更优雅的异步处理。
let
/ const
:块级作用域变量。
默认参数:
function greet(name = "Guest") {
console.log(`Hello, ${name}`);
}
Node.js:JavaScript 运行时,用于后端开发。
npm / yarn:包管理工具。
前端框架:
React:组件化开发,虚拟 DOM。
Vue.js:渐进式框架,响应式数据绑定。
Angular:全功能框架,依赖注入。