提问者:小点点

无法通过代理对象访问类方法


就像标题I can't access class method through a proxy object一样,我得到了错误

TypeError: sth.getNumber is not a function

但在我看到它像属性一样被访问之前,因为我在终端中看到了“get”log

我真的不知道为什么会这样。下面是我想要做的简单例子。提前感谢你的帮助

class mockClass {
  sth?: number
  constructor(n?: number) {
    this.sth = n
  }
  public getNumber(n: number) {
    return n
  }
}

const sth = new Proxy<any>(new mockClass(15), {
  apply: function (target, thisArg, argArr) {
    console.log("apply")
    console.log(target, thisArg, argArr)
    return "a"
  },
  get: function (target, reciver) {
    console.log("get")
    console.log(target, reciver)
    return "b"
  },
})

console.log(sth.getNumber(15))

共1个答案

匿名用户

更改:

get: function (target, reciver) {
    console.log("get")
    console.log(target, reciver)
    return "b"
  },

致:

get: function (target, reciver) {
    console.log("get")
    console.log(target, reciver)
    return () => { return "b"}
  },