面试题答案
一键面试核心代码结构
- 定义
ComplexModule
类
class ComplexModule {
// 假设这里有一些模块级别的属性
moduleProperty: string;
constructor() {
this.moduleProperty = 'default value';
}
executeWorkflow() {
// 定义一系列异步任务
const tasks: ((this: any) => Promise<void>)[] = [];
// 添加任务
tasks.push(this.task1.bind(this));
tasks.push(this.task2.bind(this));
// 按顺序执行任务
async function executeTasks() {
for (const task of tasks) {
await task();
}
}
executeTasks();
}
task1(this: ComplexModule): Promise<void> {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`Task 1 in ComplexModule, moduleProperty: ${this.moduleProperty}`);
resolve();
}, 1000);
});
}
task2(this: ComplexModule): Promise<void> {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`Task 2 in ComplexModule, moduleProperty: ${this.moduleProperty}`);
resolve();
}, 1000);
});
}
}
- 特定任务上下文对象及相关任务
// 定义特定任务上下文对象
interface TaskContext {
contextProperty: string;
contextMethod(): void;
}
class SpecificTaskContext implements TaskContext {
contextProperty = 'context value';
contextMethod() {
console.log('Context method called');
}
}
class ComplexModule {
//... 前面的代码不变
executeWorkflow() {
const tasks: ((this: any) => Promise<void>)[] = [];
tasks.push(this.task1.bind(this));
const context = new SpecificTaskContext();
tasks.push(this.taskWithContext.bind(context));
tasks.push(this.task2.bind(this));
async function executeTasks() {
for (const task of tasks) {
await task();
}
}
executeTasks();
}
taskWithContext(this: TaskContext): Promise<void> {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`Task in specific context, contextProperty: ${this.contextProperty}`);
this.contextMethod();
resolve();
}, 1000);
});
}
}
关键类型定义
ComplexModule
类型
class ComplexModule {
moduleProperty: string;
constructor() {
this.moduleProperty = 'default value';
}
// 这里可以定义更多模块级别的方法和属性
}
TaskContext
类型
interface TaskContext {
contextProperty: string;
contextMethod(): void;
}
这样设计通过 bind
方法来确保每个回调函数中的 this
指向正确的对象,同时使用类型定义来明确 this
的类型,提高代码的可维护性和扩展性。