JavaScript 类初始化详解
在 JavaScript 中,类初始化主要涉及创建类的实例并设置初始状态。以下是关于 JavaScript 类初始化的全面指南:
一、基本类初始化
1. 使用构造函数初始化
class Person {
constructor(name, age) {
this.name = name; // 初始化实例属性
this.age = age;
}
}
const person = new Person('Alice', 30);
2. 默认参数值
class Person {
constructor(name = 'Anonymous', age = 0) {
this.name = name;
this.age = age;
}
}
const unknown = new Person(); // 使用默认值
二、字段初始化(ES2022+)
1. 公共字段初始化
class Person {
name = 'Anonymous'; // 公共类字段
age = 0;
constructor(name, age) {
if (name) this.name = name;
if (age) this.age = age;
}
}
2. 私有字段初始化
class Person {
#privateId; // 私有字段声明
constructor(id) {
this.#privateId = id;
}
getId() {
return this.#privateId;
}
}
三、静态初始化
1. 静态属性初始化
class Config {
static apiUrl = 'https://api.example.com';
static timeout = 5000;
}
2. 静态初始化块(ES2022+)
class Config {
static apiUrl;
static timeout;
static {
// 复杂的静态初始化逻辑
this.apiUrl = process.env.API_URL || 'https://api.example.com';
this.timeout = parseInt(process.env.TIMEOUT) || 5000;
}
}
四、继承中的初始化
1. 调用父类构造函数
class Employee extends Person {
constructor(name, age, position) {
super(name, age); // 必须先调用super()
this.position = position;
}
}
2. 继承字段初始化
class Animal {
legs = 4;
}
class Dog extends Animal {
sound = 'bark';
constructor(breed) {
super();
this.breed = breed;
}
}
五、高级初始化技术
1. 基于工厂方法的初始化
class Product {
constructor(id, name) {
this.id = id;
this.name = name;
}
static createFromJSON(json) {
const data = JSON.parse(json);
return new Product(data.id, data.name);
}
}
const product = Product.createFromJSON('{"id":1,"name":"Laptop"}');
2. 惰性初始化
class Cache {
#data = null;
get data() {
if (!this.#data) {
this.#data = this.#loadData();
}
return this.#data;
}
#loadData() {
// 昂贵的初始化操作
return fetch('/api/data').then(r => r.json());
}
}
六、初始化顺序
JavaScript 类初始化的执行顺序:
- 父类字段初始化
- 父类构造函数
- 子类字段初始化
- 子类构造函数
class Parent {
field1 = console.log('Parent field');
constructor() {
console.log('Parent constructor');
}
}
class Child extends Parent {
field2 = console.log('Child field');
constructor() {
super();
console.log('Child constructor');
}
}
new Child();
// 输出顺序:
// Parent field
// Parent constructor
// Child field
// Child constructor
七、错误处理
1. 构造函数中的错误处理
class Resource {
constructor(url) {
try {
if (!url) throw new Error('URL is required');
this.url = url;
} catch (error) {
console.error('Initialization failed:', error);
throw error; // 可以选择重新抛出
}
}
}
2. 异步初始化
class Database {
constructor() {
this.connection = null;
}
async init() {
this.connection = await connectToDatabase();
return this;
}
}
// 使用方式
const db = await new Database().init();
八、最佳实践
- 保持构造函数简单:只做必要的初始化,复杂逻辑放在单独方法中
- 使用明确的初始化方法:对于复杂对象,提供
init()方法 - 优先使用类字段:使属性初始化更清晰
- 考虑不可变性:初始化后不应更改的属性使用
Object.freeze() - 文档化初始化要求:明确说明类初始化需要的参数和条件
九、实际应用示例
1. 配置对象初始化
class AppConfig {
constructor(options = {}) {
const defaults = {
env: 'development',
debug: false,
apiBase: '/api/v1'
};
this.config = {...defaults, ...options};
}
}
2. 带验证的初始化
class User {
constructor(userData) {
this.validate(userData);
this.id = userData.id;
this.email = userData.email;
}
validate(data) {
if (!data.id) throw new Error('ID is required');
if (!this.isValidEmail(data.email)) {
throw new Error('Invalid email');
}
}
isValidEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
}
3. 组合式初始化
class Widget {
constructor() {
this.components = [];
}
addComponent(component) {
this.components.push(component);
return this; // 支持链式调用
}
}
const widget = new Widget()
.addComponent(new Button())
.addComponent(new Slider());
1359

被折叠的 条评论
为什么被折叠?



