gpt4 book ai didi

javascript - 代理无法在扩展类中获取方法

转载 作者:行者123 更新时间:2023-11-30 14:52:46 25 4
gpt4 key购买 nike

我正在尝试使用 Proxy,但遇到了问题。我有这样的类(class):

export class Builder {
public doSomething(...args: (string | number | Raw | Object)[]): this {
// Do stuff
return this
}
}

export class ModelBase extends Builder {
protected _items = {}
}

export class Model extends ModelBase {

public constructor(options?: ModelSettings) {
super(options)
return new Proxy(this, {
get: function (target, property) {
return target._items[property] || target
}
})
}

public static create() {
return new this()
}

}

然后我像这样扩展 Model:

export class MyClass extends Model {

public constructor() {
super({/* Some options go here */})
// Do some stuff
}

public static getItems() {
let t = this.create()
t.doSomething()
}

}

然后我调用 getItems() 创建类的一个实例。

MyClass.getItems()

当我运行它时,出现错误:

TypeError: t.doSomething is not a function

doSomething() 在类 ModelBase 中。如果我注释掉 Proxy 一切照常进行。所以,我想知道为什么我不能访问父类。

最佳答案

您的代理正在尝试查找 target._items.doSomething,但它不存在。 target.doSomething 确实存在,但它不是在寻找那个。结果,它退回到返回 target,这是整个对象。对象不是函数,因此是错误。

至于如何解决这个问题,这取决于您试图通过代理实现的目标。如果代理应该注意一组有限的属性,您可以明确检查这些属性。或者更一般地说,您可以检查 target[property] 是否存在,然后回退到 target._items[property] 然后才回退到 target 。同样,这取决于您要实现的目标。

关于javascript - 代理无法在扩展类中获取方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47879152/

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