gpt4 book ai didi

javascript - 如何将类构造函数的 "this"绑定(bind)到外部对象

转载 作者:行者123 更新时间:2023-12-03 07:09:59 26 4
gpt4 key购买 nike

我正在寻找一种方法来为类使用类似于 Function.apply 的东西,以便执行的构造函数的 this 属性是一个外部对象。

有了一个函数,我可以简单地使用 apply

function Bar() {
this.value = 'value'
}

const proxy = {}
Bar.apply(proxy, [])

console.log(proxy) // { value: 'value' }

当然,这不适用于类

class Foo {
constructor() {
this.value = 'value'
}
}

const proxy = {}
Foo.apply(proxy, [])

console.log(proxy)

导致

Foo.apply(proxy, [])
^
TypeError: Class constructor Foo cannot be invoked without 'new'

是否可以将类构造函数的 this 上下文绑定(bind)到另一个对象?

我没有任何遗留客户端,所以我可以使用 Reflect.construct(虽然我不确定它是否可以解决问题)

编辑:

或者,我可以在构建后替换 this。这可能吗?

const foo = new Foo()
foo.bind(proxy)

最佳答案

如果你看看[[Construct]]函数对象(这是当您使用 newReflect.construct 时将执行的内部方法),那么您会在规范中找到这一步:

Let thisArgument be ? OrdinaryCreateFromConstructor(newTarget, "%Object.prototype%").

由于无法更改此行为,因此您无法更改 thisArgument 是什么,它始终是常规对象,不能是代理。但是,如果您使用 Reflect.construct,您可以影响 newTarget,并在常规构造函数中传递其他内容:

class Constructed {} // this is the function object that will be [[Construct]]ed
class Trapped {} // the "thisArgument" will inherit Trapped.prototype

Reflect.construct(Constructed, [], Trapped);

通过将代理注入(inject) Trapped.prototype,您可以在类构造函数中对 this 进行一些反射(reflection)。可以找到一个例子here .

关于javascript - 如何将类构造函数的 "this"绑定(bind)到外部对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64714673/

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