Home > Mobile >  How to rewrite class to plain object?
How to rewrite class to plain object?

Time:10-26

How would one rewrite this class to a plain object?

class ExampleClass {
    firstPropery: number = 0;
    secondProperty!: string;

  async exampleMethod(): Promise<void> {
    const { secondProperty } = await SomeHelperClass.exampleRequest();
    this.secondProperty = secondProperty;
  }
}

I would think it's something similar as this

interface IExample {
  firstProperty: number;
  secondProperty: string;
  exampleMethod: () => Promise<void>;
}

const Example: IExample = {
  firstProperty: 0,
  exampleMethod: async (): Promise<void> => {
    const { secondProperty } = await SomeHelperClass.exampleRequest();
    ...
  }
}

But how to set the secondProperty via the exampleMethod? In the class method I can just write this.secondProperty = ..., which I cannot do in the plain object.

My second question is, with the class I would make a new object like this const newObject = new ExampleClass();. With the plain object way, how would I make a new object instance?

Any help is gladly appreciated!

CodePudding user response:

In the class method I can just write this.secondProperty = ..., which I cannot do in the plain object.

Actually you can. It doesn't matter whether it's defined in a class or object literal, exampleMethod is still a method and when called as example.exampleMethod() it will have its this point to example. However, you cannot use an arrow function to define it - use method syntax instead:

const example: IExample = {
  firstProperty: 0,
  async exampleMethod(): Promise<void> {
    const { secondProperty } = await SomeHelperClass.exampleRequest();
    ...
  }
}

With the class I would make a new object like this const newObject = new ExampleClass();. With the plain object way, how would I make a new object instance?

You write the code again and again. Or you use Object.assign to copy the method onto a new object. Or you place the object literal inside a function that you can call multiple times.

  • Related