![](/img/trans.png)
[英]How do I retain the properties of a Javascript object while changing the object's constructor to an instance function
[英]How do I spread an object (class instance properties) to the parent's super constructor?
如何將 class 屬性傳播到父級的超級構造函數?
ActionLog 是一個基礎 class,它在 ActionRequestAccess 內部的方法中實例化
ActionRequestAccess.ts
export class ActionRequestAccess extends ActionLog {
constructor(public actionLog: ActionLog, public customerId: string) {
super(
actionLog.id, // Want to get rid of these assignments <<< and switch to something like: ...actionLog
actionLog.type,
actionLog.date,
actionLog.address,
actionLog.location
);
}
static override fromMap(map: any) {
if (!map) {
return null;
}
const baseMap = super.fromMap(map);
if (!baseMap) {
return null;
}
return new ActionRequestAccess(baseMap, map['customerId'] ?? null);
}
}
動作日志.ts
import { ActionType } from '../../enums';
export class ActionLog {
constructor(
public id: string,
public type: ActionType,
public date: Date,
public address: string,
public location: string
) {}
static fromMap(map: any) {
if (!map) {
return null;
}
return new ActionLog(
map['id'] ?? null,
map['type'] ?? null,
map['date'] ?? null,
map['address'] ?? null,
map['location'] ?? null
);
}
}
您可以在ActionRequestAccess
內的 object 上使用Object.values
。
constructor(public actionLog: ActionLog, public customerId: string) {
super(...Object.values(actionLog));
}
但這意味着您的 object 的值的順序傳遞給 function 數學,所以這種模式有點不安全。 這將起作用
const myObject = new ActionRequestAccess({
id: 1,
type: 'myType',
date: 'myDate',
adress: 'myAdress',
location: 'myLocation',
});
但這會切換 id 和 type 的 position 並且不起作用。
const myObject = new ActionRequestAccess({
type: 'myType',
id: 1,
date: 'myDate',
adress: 'myAdress',
location: 'myLocation',
});
如果您可以將ActionLog
的構造函數的預期值更改為 object 而不是參數,那么這可能會更容易和更安全。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.