如何绑定"this"类构造函数到外部对象的说明 [英] How to bind the "this" of a class constructor to an external object

查看:38
本文介绍了如何绑定"this"类构造函数到外部对象的说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking for a way to use something similar to Function.apply for classes so that the this property of an executed constructor is an external object.

有了功能,我可以简单地使用 apply

With a function I can simply use apply

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

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

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

但是,这当然不适用于类

However this does not, of course, work with classes

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 上下文绑定到另一个对象?

Is it possible to bind the this context of a class constructor to another object?

我没有任何旧版客户端,因此可以使用 Reflect.construct (尽管我不确定它是否可以解决问题)

I don't have any legacy clients so I am able to use Reflect.construct (though I am not sure if it can solve the problem)

或者,我可以在构造后替换 this .有可能吗?

Alternatively, I can work with replacing this after construction. Is that possible?

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

推荐答案

如果您查看

If you have a look at [[Construct]] of function objects (which is the internal method which will be executed when you use new or Reflect.construct), then you'll find this step in the specification:

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

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

As there is no way to change this behavior, you cannot change what thisArgument is, it is always a regular object and cannot be a proxy. However, if you use Reflect.construct, you can influence the newTarget, and pass something else in than the regular constructor:

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

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

通过将代理注入到 Trapped.prototype 中,您可以对类构造函数中的 this 有所了解.可以在此处找到一个示例.

By injecting a proxy into Trapped.prototype you can have some reflection onto this inside a class constructor. An example can be found here.

这篇关于如何绑定"this"类构造函数到外部对象的说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆