2016-11-21 63 views
2

問題:我想通過向其中定義的對象添加其他屬性來擴展一個類。這裏的情景:如何在類中擴展對象定義?

我有以下類中定義:

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

我使用這個類作爲構建模塊下面的類

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 
    } 
} 

有關如何避免在最後SitePropertiesDetails類中重複name屬性的任何想法,通過某種方式擴展原始SiteProperties類?

+1

是不是有一個原因,你有類中的'屬性'對象,而不是隻是使該類的'屬性'對象成員的成員? –

+0

你必須給它當前的匿名對象自己的類('SitePropertiesProperties'?),以便你可以繼承它。 – Bergi

回答

1

由於James Monger指出,也許這是不是要走的路?

如果這是你想要的東西,那麼你可以使用帶有可選參數接口來定義你properties對象:

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

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

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

 

 
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);

0

我想說最好的OOP方法是做類的本身,而不是匿名對象。

export class SiteProperties { 
    name: string; 
} 

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

export class SitePropertiesDetails extends SiteProperties { 
    description: string; 
} 

let x = new SitePropertiesDetails(); 
x.name = "Site Number One"; 
x.description = "The best site there is!"; 

正如你所看到的,SitePropertiesDetails既有namedescription。這是否符合您的需求?