如何将TypeScript类重写为普通对象并实现同等功能?
问题1:如何在对象方法中修改自身属性
你遇到this无法使用的核心原因是你用了箭头函数定义exampleMethod:箭头函数没有独立的this绑定,其this指向定义时的外层作用域,而非当前对象。
有两种解决方式:
- 改用普通函数语法定义方法,此时
this会指向当前调用方法的对象:
const example = { secondProperty: undefined, // 用普通函数语法 async exampleMethod() { const res = await SomeHelperClass.exampleRequest(); this.secondProperty = res.secondProperty; } }
- 搭配工厂函数用闭包直接引用实例对象,避免this丢失问题(适合方法需要被解构传递的场景):
function createExample() { // 先声明实例变量 const instance = { secondProperty: undefined, // 箭头函数可以直接引用上层的instance变量 exampleMethod: async () => { const res = await SomeHelperClass.exampleRequest(); instance.secondProperty = res.secondProperty; } } return instance; }
问题2:如何创建多个独立实例
使用工厂函数即可完全替代类的new调用:工厂函数每次调用都会返回一个全新的独立对象,不同实例之间的属性互不干扰。
完整的TypeScript实现如下:
interface IExample { firstProperty: number; secondProperty: string | undefined; exampleMethod: () => Promise<void>; } function createExample(): IExample { const instance = { firstProperty: 0, secondProperty: undefined, exampleMethod: async () => { const { secondProperty } = await SomeHelperClass.exampleRequest(); instance.secondProperty = secondProperty; } } return instance; } // 使用方式和new类完全一致 const newObject = createExample(); // 调用方法 await newObject.exampleMethod(); // 可以访问属性 console.log(newObject.secondProperty);
内容的提问来源于stack exchange,提问作者PTheory
相关产品推荐
相关产品推荐

