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

标签 javascript oop typescript ecmascript-6

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

我定义了以下类:

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/

相关文章:

javascript - 如何缩短 typescript 中的界面名称?

javascript - 如何使用 React 内置的 React.memo 比较功能?

oop - 差异聚合、相识和组合(如四人帮所用)

javascript - 如何在迭代循环时传递真实值?

javascript - 面向对象的Javascript中公共(public)函数和使用原型(prototype)添加的函数有什么区别

javascript - 从动态创建的子构造函数调用父构造函数

angular - TypeScript 模块扩充

用于拆分数据和计算总和的 JavaScript

javascript - Jquery $.ajax 在错误处理程序中返回未定义的 jqXHR

javascript - 这在 JavaScript : var controller = controller || {}; 中意味着什么