如何使用Proxy在Node.js中模拟PHP的__callStatic属性



我正试图在Node.js.中创建与PHP__callStatic魔术方法相同的行为

我正在尝试使用Proxy来做到这一点,但我真的不知道这是否是最好的选择。

class Test {
constructor() {
this.num = 0
}

set(num) {
this.num = this.num + num
return this
}

get() {
return this.num
}
}
const TestFacade = new Proxy({}, {
get: (_, key) => {
const test = new Test()

return test[key]
}
})

// Execution method chain ends in get
console.log(TestFacade.set(10).set(20).get())
// expected: 30
// returns: 0
// Start a new execution method chain and should instantiate Test class again in the first set
console.log(TestFacade.set(20).set(20).get())
// expected: 40
// returns: 0

问题是每次我尝试访问TestFacade的属性时都会触发get陷阱。我需要的行为是,当调用set方法时,它将返回Test类的this,我甚至可以保存该实例以供以后使用!

const testInstance = TestFacade.set(10) // set method return this of `Test` not the Proxy

如果有什么不清楚的地方,请告诉我。

我不知道这是否是最好的选择。但我解决了这个问题,在get陷阱中返回了一个新的Proxy,该陷阱使用apply陷阱将test类实例绑定到方法中:

class Facade {
static #facadeAccessor
static createFacadeFor(provider) {
this.#facadeAccessor = provider
return new Proxy(this, { get: this.__callStatic.bind(this) })
}
static __callStatic(facade, key) {
/**
* Access methods from the Facade class instead of
* the provider.
*/
if (facade[key]) {
return facade[key]
}
const provider = new this.#facadeAccessor()
const apply = (method, _this, args) => method.bind(provider)(...args)
if (provider[key] === undefined) {
return undefined
}
/**
* Access the properties of the class.
*/
if (typeof provider[key] !== 'function') {
return provider[key]
}
return new Proxy(provider[key], { apply })
}
}
class Test {
num = 0
set(num) {
this.num = this.num + num
return this
}
get() {
return this.num
}
}
const TestFacade = Facade.createFacadeFor(Test)
console.log(TestFacade.set(10).set(20).get()) // 30
console.log(TestFacade.set(5).set(5).get()) // 10
const testInstance = TestFacade.set(10)
console.log(testInstance.num) // 10
console.log(testInstance.get()) // 10
console.log(testInstance.set(10).get()) // 20

最新更新