javascript - 是否可以在 JS 中重新创建 "new"运算符?

标签 javascript reflection

我最近读了MDN documentation on the new operator ,它的作用的简洁描述让我震惊:

When the code new Foo(...) is executed, the following things happen:

  1. A new object is created, inheriting from Foo.prototype.
  2. The constructor function Foo is called with the specified arguments and this bound to the newly created object. new Foo is equivalent to new Foo(), i.e. if no argument list is specified, Foo is called without arguments.
  3. The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

看起来这些都不是特权操作,那么是否可以完全重新创建 new 的操作与其他语言结构?

请注意,我没有算 Reflect.construct 因为它的定义就是“就像 new 运算符一样作为函数”。

最佳答案

这个函数几乎重新创建了 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
}

这里是the same code presented alongside some test cases .

关于javascript - 是否可以在 JS 中重新创建 "new"运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34928689/

相关文章:

javascript - 如何切换 jQuery 中的就地编辑功能?

javascript - 使用 jQuery Cookie 来存储复选框状态

C# 将 Dictionary<string, AnyType> 转换为 Dictionary<string, Object> (涉及反射)

c# - 在 Windows CE 中创建对象实例比反射更快

java - Caused by : java. lang.ClassCastException : java. lang.Class无法转换为java.lang.reflect.ParameterizedType

javascript - 智能 : Live Template to replace callback function with an es6 array function

javascript - 根据数据属性更改 d3.js 符号大小

javascript - 在YouTube视频上使用带有fancybox的jQuery…但是Youtube控件不起作用?

java - newInstance() 的实例化异常

reflection - EJB 中是否允许反射?