2016-01-21 103 views
1

最近,我读了MDN documentation on the new operator,我被它用来做什么的简洁描述来袭:是否有可能在JS中重新创建“新”运算符?

当执行代码新(...),下面的事情发生:

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

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

请注意,我不计数Reflect.construct,因为它的定义是“它像新函数一样起作用”。

+1

公告自ES6以来,你必须使用'Reflect.construct',上面的描述来自ES5,一些内建函数和使用'class'语法*定义的构造函数区分被调用为构造函数和被调用的方法 – Bergi

回答

1

此功能非常再现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

+1

不要相信检测对象时检测'typeof'。它可能会为不可召回的非标准外来物体返回奇怪的东西,例如, ' “未知”'。 Object(retVal)=== retVal'更可靠。 – Oriol

相关问题