gpt4 book ai didi

javascript - 如何在类中扩展对象定义?

转载 作者:搜寻专家 更新时间:2023-10-30 21:52:33 24 4
gpt4 key购买 nike

问题:我想通过向类中定义的对象添加附加属性来扩展类。场景如下:

我定义了以下类:

export class SiteProperties {
properties : {
name: string;
}
}

我用这个类作为下一个类的构建 block

export class Site extends SiteProperties {
parent : SiteProperties[];
online: number;
issues: number;
}

问题是我想扩展 SiteProperties 以在“属性”对象中包含其他字段,以便它变成:

export class SitePropertiesDetails { 
properties : {
name: string,
description: string // I basically want to add this field by extending the first SiteProperties class I created
}
}

关于如何通过以某种方式扩展原始 SiteProperties 类来避免在最后一个 SitePropertiesDetails 类中重复 name 属性有什么想法吗?

最佳答案

作为James Monger指出,也许这不是要走的路?

如果这是你想要的,那么你可以使用带有可选参数的接口(interface)来定义你的 properties 对象:

interface ISiteProperties {
parent?: SiteProperties[];
online?: number;
issues?: number;
name?: string;
description?: string;
}

class SiteProperties {
public properties: ISiteProperties = {};
constructor() {
this.properties.name = "Test name";
}
}

class Site extends SiteProperties {
constructor() {
super();
this.properties.online = 123;
this.properties.issues = 321;
}
}


var obj1 = new SiteProperties(), obj2 = new Site();

console.log(obj1);
console.log(obj2);

和 javascript 版本:

var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var SiteProperties = (function () {
function SiteProperties() {
this.properties = {};
this.properties.name = "Test name";
}
return SiteProperties;
}());
var Site = (function (_super) {
__extends(Site, _super);
function Site() {
_super.call(this);
this.properties.online = 123;
this.properties.issues = 321;
}
return Site;
}(SiteProperties));
var obj1 = new SiteProperties(), obj2 = new Site();
console.log(obj1);
console.log(obj2);

关于javascript - 如何在类中扩展对象定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40723960/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com