JavaScript 内置对象

JavaScript 内置对象的分类与常用方法

问题

介绍 JavaScript 有哪些内置对象?

解答

JavaScript 内置对象可分为以下几类:

1. 基本对象

// Object - 所有对象的基类
const obj = new Object();
Object.keys({ a: 1, b: 2 }); // ['a', 'b']

// Function - 函数对象
const fn = new Function('a', 'b', 'return a + b');
fn(1, 2); // 3

// Boolean
const bool = new Boolean(true);

// Symbol - 唯一标识符
const sym = Symbol('description');

2. 数值与数学

// Number
Number.isInteger(5);      // true
Number.parseFloat('3.14'); // 3.14

// Math - 数学计算(静态对象,不能 new)
Math.max(1, 2, 3);    // 3
Math.floor(3.7);      // 3
Math.random();        // 0-1 随机数

// BigInt - 大整数
const big = BigInt(9007199254740991);
const big2 = 9007199254740991n;

3. 日期

// Date
const now = new Date();
now.getFullYear();    // 2024
now.getMonth();       // 0-11
now.getDate();        // 1-31
now.getTime();        // 时间戳

4. 字符串与正则

// String
'hello'.toUpperCase();     // 'HELLO'
'hello'.includes('ell');   // true
'a,b,c'.split(',');        // ['a', 'b', 'c']

// RegExp
const reg = /\d+/g;
'a1b2'.match(reg);         // ['1', '2']

5. 集合类型

// Array
const arr = [1, 2, 3];
arr.map(x => x * 2);       // [2, 4, 6]
arr.filter(x => x > 1);    // [2, 3]

// Map - 键值对集合
const map = new Map();
map.set('key', 'value');
map.get('key');            // 'value'

// Set - 唯一值集合
const set = new Set([1, 2, 2, 3]);
[...set];                  // [1, 2, 3]

// WeakMap / WeakSet - 弱引用版本,键必须是对象
const wm = new WeakMap();
const wm_key = {};
wm.set(wm_key, 'data');

6. 结构化数据

// JSON
JSON.stringify({ a: 1 });  // '{"a":1}'
JSON.parse('{"a":1}');     // { a: 1 }

// ArrayBuffer - 二进制数据缓冲区
const buffer = new ArrayBuffer(16);
const view = new DataView(buffer);
view.setInt8(0, 42);

7. 控制抽象

// Promise - 异步操作
const promise = new Promise((resolve, reject) => {
  setTimeout(() => resolve('done'), 1000);
});
promise.then(console.log);

// Generator - 生成器
function* gen() {
  yield 1;
  yield 2;
}
const g = gen();
g.next(); // { value: 1, done: false }

8. 反射与代理

// Reflect - 反射操作
Reflect.has({ a: 1 }, 'a');        // true
Reflect.get({ a: 1 }, 'a');        // 1

// Proxy - 对象代理
const proxy = new Proxy({ a: 1 }, {
  get(target, prop) {
    console.log(`访问 ${prop}`);
    return target[prop];
  }
});
proxy.a; // 打印 "访问 a",返回 1

9. 错误对象

// Error 及其子类
new Error('通用错误');
new TypeError('类型错误');
new ReferenceError('引用错误');
new SyntaxError('语法错误');
new RangeError('范围错误');

关键点

  • 基本对象:Object、Function、Boolean、Symbol 是构建其他对象的基础
  • Math 是静态对象:直接调用方法,不能 new
  • Map/Set vs WeakMap/WeakSet:弱引用版本的键必须是对象,且不阻止垃圾回收
  • Proxy/Reflect:ES6 新增,用于元编程和对象拦截
  • 全局对象:浏览器中是 window,Node.js 中是 global,通用写法是 globalThis