JavaScript
2026/1/15大约 3 分钟
JavaScript
数据类型
基本类型
// 7种基本类型
string, number, boolean, null, undefined, symbol, bigint
// 类型判断
typeof 'str' // 'string'
typeof 123 // 'number'
typeof true // 'boolean'
typeof undefined // 'undefined'
typeof Symbol() // 'symbol'
typeof null // 'object' (历史遗留bug)
typeof {} // 'object'
typeof [] // 'object'
// 准确判断
Object.prototype.toString.call([]) // '[object Array]'
Array.isArray([]) // true类型转换
// 转数字
Number('123') // 123
parseInt('123px') // 123
+'123' // 123
// 转字符串
String(123) // '123'
123 + '' // '123'
// 转布尔
Boolean(0) // false
!!1 // true
// 假值:false, 0, '', null, undefined, NaN作用域与闭包
作用域
// 全局作用域
var global = 'global';
// 函数作用域
function fn() {
var local = 'local';
}
// 块级作用域(let/const)
{
let block = 'block';
const CONST = 'const';
}闭包
// 闭包:函数能够访问其词法作用域外的变量
function outer() {
let count = 0;
return function inner() {
return ++count;
};
}
const counter = outer();
counter(); // 1
counter(); // 2
// 应用:模块化、柯里化、防抖节流防抖与节流
// 防抖:最后一次触发后延迟执行
function debounce(fn, delay) {
let timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
// 节流:固定时间间隔执行
function throttle(fn, delay) {
let last = 0;
return function(...args) {
const now = Date.now();
if (now - last >= delay) {
last = now;
fn.apply(this, args);
}
};
}原型与继承
原型链
function Person(name) {
this.name = name;
}
Person.prototype.sayHi = function() {
console.log('Hi, ' + this.name);
};
const p = new Person('Tom');
p.sayHi();
// 原型链
p.__proto__ === Person.prototype
Person.prototype.__proto__ === Object.prototype
Object.prototype.__proto__ === nullES6 Class
class Person {
constructor(name) {
this.name = name;
}
sayHi() {
console.log('Hi, ' + this.name);
}
static create(name) {
return new Person(name);
}
}
class Student extends Person {
constructor(name, grade) {
super(name);
this.grade = grade;
}
}this 指向
// 1. 默认绑定:全局对象(严格模式 undefined)
function fn() { console.log(this); }
fn(); // window
// 2. 隐式绑定:调用对象
obj.fn(); // obj
// 3. 显式绑定:call/apply/bind
fn.call(obj);
fn.apply(obj, [args]);
fn.bind(obj)();
// 4. new 绑定:新创建的对象
new Fn();
// 5. 箭头函数:继承外层 this
const arrow = () => console.log(this);异步编程
Promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('success'), 1000);
});
promise
.then(res => console.log(res))
.catch(err => console.error(err))
.finally(() => console.log('done'));
// Promise 方法
Promise.all([p1, p2, p3]); // 全部成功
Promise.race([p1, p2, p3]); // 最快的
Promise.allSettled([p1, p2]); // 全部完成
Promise.any([p1, p2, p3]); // 任一成功async/await
async function fetchData() {
try {
const res = await fetch('/api/data');
const data = await res.json();
return data;
} catch (error) {
console.error(error);
}
}
// 并行请求
const [user, posts] = await Promise.all([
fetchUser(),
fetchPosts()
]);ES6+ 特性
解构赋值
// 数组解构
const [a, b, ...rest] = [1, 2, 3, 4];
// 对象解构
const { name, age = 18 } = { name: 'Tom' };
// 函数参数解构
function fn({ name, age }) {}展开运算符
// 数组
const arr = [...arr1, ...arr2];
// 对象
const obj = { ...obj1, ...obj2 };
// 函数参数
fn(...args);可选链与空值合并
// 可选链
const name = user?.profile?.name;
const fn = obj?.method?.();
// 空值合并
const value = data ?? 'default'; // 仅 null/undefined 时使用默认值其他特性
// 模板字符串
const str = `Hello, ${name}!`;
// 箭头函数
const fn = (x) => x * 2;
// 默认参数
function fn(x = 1) {}
// Map/Set
const map = new Map([['key', 'value']]);
const set = new Set([1, 2, 3]);
// Symbol
const sym = Symbol('description');
// Proxy
const proxy = new Proxy(target, handler);事件循环
// 宏任务:setTimeout, setInterval, I/O, UI渲染
// 微任务:Promise.then, MutationObserver, queueMicrotask
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');
// 输出:1, 4, 3, 2手写实现
深拷贝
function deepClone(obj, map = new WeakMap()) {
if (obj === null || typeof obj !== 'object') return obj;
if (map.has(obj)) return map.get(obj);
const clone = Array.isArray(obj) ? [] : {};
map.set(obj, clone);
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
clone[key] = deepClone(obj[key], map);
}
}
return clone;
}实现 call/apply/bind
Function.prototype.myCall = function(context, ...args) {
context = context || window;
const fn = Symbol();
context[fn] = this;
const result = context[fn](...args);
delete context[fn];
return result;
};
Function.prototype.myBind = function(context, ...args) {
const fn = this;
return function(...newArgs) {
return fn.apply(context, [...args, ...newArgs]);
};
};实现 new
function myNew(Constructor, ...args) {
const obj = Object.create(Constructor.prototype);
const result = Constructor.apply(obj, args);
return result instanceof Object ? result : obj;
}