![](/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.