Javascript Object.create未运行构造函数
我试图在一个静态方法中创建一个类的实例,我使用Javascript Object.create未运行构造函数,javascript,typescript,Javascript,Typescript,我试图在一个静态方法中创建一个类的实例,我使用对象来创建(this.prototype)这似乎是可行的,但是,当我将属性记录到控制台时,我的属性项是未定义的 我有一个名为model的类,它是基础: export default class model { protected items: any = {} public constructor(options: ModelSettings) { // Do some stuff // Does not set the
对象来创建(this.prototype)
这似乎是可行的,但是,当我将属性记录到控制台时,我的属性项
是未定义的
我有一个名为model的类,它是基础:
export default class model {
protected items: any = {}
public constructor(options: ModelSettings) {
// Do some stuff
// Does not set the property items before it is compiled
}
public static create(options) {
let t = Object.create(this.prototype) as any
console.log(t.items)
}
}
然后我有一个扩展模型的类:
export default class purchases extends model {
public constructor() {
super({table: 'purchases'})
}
}
然后我这样称呼它:
purchases.create({ my: 'options' })
create方法创建purchases
的一个实例,该实例似乎有效,但是属性items
是未定义的
,就像我前面提到的那样
是否Object.create()
没有运行构造函数?它不会调用构造函数。它只是创建了一个没有强类型{}
的对象,如下所示
const obj = {}
把这个物体的原型放到给定的原型上
您只需使用newthis()
而不是对象。create()
请参见它不调用构造函数,只设置原型。你得自己叫它
// Set prototype
let t = Object.create(this.prototype) as any;
// Call the constructor , this should point to the constructor
this.apply(this);
正如其他人提到的,您应该能够执行以下操作,并将原型链接起来并调用构造函数
t = new this();
如果你想构造一些东西,你可能应该使用new
:
let t = new this;
如果您真的想手动执行此操作,则会有点复杂:
let t = Object.create(this.prototype);
this.call(t);
为什么不使用newmodel()
而不是对象。创建new model()
肯定会调用构造函数,因为我不想要一个新的model
,我想要一个新的purchases
,然后我想在itI上设置一些额外的“设置”选项,我可以调用方法,所以必须复制这些方法。有什么方法可以让我运行构造函数吗?我想你可以做newthis()
而不是对象。创建