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

问题描述 投票:1回答:1

我正在尝试使用Proxy,我遇到了问题。我有一个这样的课:

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不是函数

其中doSomething()属于ModelBase类。如果我评论出Proxy事情像往常一样工作。所以,我想知道为什么我无法访问父类。

javascript typescript ecmascript-6 es6-proxy
1个回答
2
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.