Javascript 在TypeScript中具有config对象的构造函数(如jQuery.extend、Ext.apply)
在TypeScript/ECMAScript6中,用另一个对象扩展任意对象的等效性是什么 基本上类似于jQuery中的Javascript 在TypeScript中具有config对象的构造函数(如jQuery.extend、Ext.apply),javascript,constructor,configuration,typescript,Javascript,Constructor,Configuration,Typescript,在TypeScript/ECMAScript6中,用另一个对象扩展任意对象的等效性是什么 基本上类似于jQuery中的$.extend(target,src),或者extjsdo中的Ext.apply(target,src,defaults) 我想要一个类构造函数,它只将配置对象应用到构造函数创建的对象实例上,如下所示: class Address { country: string; postCode: string; city: stri
$.extend(target,src)
,或者extjsdo中的Ext.apply(target,src,defaults)
我想要一个类构造函数,它只将配置对象应用到构造函数创建的对象实例上,如下所示:
class Address {
country: string;
postCode: string;
city: string;
street: string;
houseNumber: string;
constructor (config : any) {
// simply tag all configuration onto the object,
// may be one, may be multiple, may be all properties
// of the resulting object instance
Object.apply(this, config); // ????
// jQuery.extend(this, config);
// Ext.apply(this, config);
this.init();
}
init () {
// do some initialization work ...
}
}
或者对于类型安全语言(如TypeScript和ECMAScript 6)来说,“对象配置模式”是不推荐的
是否有一种“新方法”可以实现同样的灵活性?您可以创建一个接口,并将其用作配置对象:
interface MyConfiguration {
country ?: string;
postCode ?: string;
city ?: string;
street ?: string;
houseNumber ?: string;
}
建造商:
constructor (config : MyConfiguration) {
// ...
}
当您实例化它时:
new Address({
country: 'US',
city: 'New york'
// all fields are optional, you only need to fill, what you want.
});
或者对于类型安全语言(如TypeScript和ECMAScript 6)来说,“对象配置模式”是不推荐的
Nit:ES6和TypeScript是不同的。这种使用模式适用于ES6
对于类型安全,您通常不能随意进行变异,也不能不告诉类型系统。这个模式与
mixins
的概念密切相关,告诉typescript关于它的方式有点冗长,但有文档记录:那么,将这个配置对象应用于创建的实例时,构造函数会是什么样子呢?我想表达的只是“将所有配置属性应用于创建的实例”(如$.extend(this,config)
)是否有用于此的TypeScript/ECMAScript语法?不知道。我要做的是,创建一个带有默认设置的配置对象,然后在构造函数中合并默认值和参数配置,而不将每个属性复制到构造的对象中,只保留对配置对象的引用,并直接从那里访问配置。检查此项