如何將此類重寫為普通物件?
class ExampleClass {
firstPropery: number = 0;
secondProperty!: string;
async exampleMethod(): Promise<void> {
const { secondProperty } = await SomeHelperClass.exampleRequest();
this.secondProperty = secondProperty;
}
}
我認為這與此類似
interface IExample {
firstProperty: number;
secondProperty: string;
exampleMethod: () => Promise<void>;
}
const Example: IExample = {
firstProperty: 0,
exampleMethod: async (): Promise<void> => {
const { secondProperty } = await SomeHelperClass.exampleRequest();
...
}
}
但是如何設定secondPropertyviaexampleMethod呢?在類方法中,我可以只寫this.secondProperty = ...,而在普通物件中卻無法做到。
我的第二個問題是,對于這個類,我會創建一個像這樣的新物件const newObject = new ExampleClass();。使用普通物件方式,我將如何創建一個新的物件實體?
任何幫助都非常感謝!
uj5u.com熱心網友回復:
在類方法中,我可以只寫
this.secondProperty = ...,而在普通物件中卻無法做到。
其實你可以。它是在類中定義還是在物件字面量中定義都沒有關系,它exampleMethod仍然是一個方法,并且在呼叫example.exampleMethod()時將this指向example. 但是,您不能使用箭頭函式來定義它- 請改用方法語法:
const example: IExample = {
firstProperty: 0,
async exampleMethod(): Promise<void> {
const { secondProperty } = await SomeHelperClass.exampleRequest();
...
}
}
使用該類,我將創建一個像這樣的新物件
const newObject = new ExampleClass();。使用普通物件方式,我將如何創建一個新的物件實體?
你一遍又一遍地撰寫代碼。或者您Object.assign用來將方法復制到新物件上。或者您將物件字面量放在一個可以多次呼叫的函式中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/336783.html
標籤:javascript 打字稿 班级 目的
