是否可以在JS中重新创建“新”运算符

Is it possible to recreate the "new" operator in JS?

本文关键字:创建 运算符 新创建 JS 是否      更新时间:2023-09-26

我最近阅读了有关new运算符的MDN文档,我对它的功能的简洁描述感到震惊:

当执行新的 Foo(...) 代码时,会发生以下情况:

  1. 创建一个新对象,继承自 Foo.prototype。
  2. 构造函数 Foo 使用指定的参数调用,并将其绑定到新创建的对象。 new Foo相当于 new Foo(),即如果没有指定参数列表,则调用Foo。 没有参数。
  3. 构造函数返回的对象将成为整个新表达式的结果。如果构造函数没有 显式返回一个对象,使用步骤 1 中创建的对象 相反。(通常构造函数不返回值,但它们可以 如果他们想要覆盖正常的对象创建,请选择这样做 过程。

似乎这些东西都不是特权操作,那么是否有可能用其他语言结构完全重新创建new的操作?

请注意,我不算Reflect.construct因为它的定义是它"像新运算符一样充当函数"。

这个函数几乎重新创建了Reflect.construct,因此new(除了construct的最后一个参数,它在使用new运算符时没有等价物:

function fauxNew (constructor, args) {
    // allocate a new object and set the prototype
    var newObject = Object.create(constructor.prototype)
    // call the constructor with "this" bound to the new object
    var retVal = constructor.apply(newObject, args || [])
    // if the constructor returned an object, return it; 
    // otherwise return the new object
    var constructorReturnedAnObject = 
        !!retVal && ["object", "function"].indexOf(typeof retVal) !== -1
    return constructorReturnedAnObject? retVal : newObject
}

下面是与一些测试用例一起提供的相同代码。