我最近读了MDN documentation on the new
operator ,它的作用的简洁描述让我震惊:
When the code new Foo(...) is executed, the following things happen:
- A new object is created, inheriting from Foo.prototype.
- The constructor function Foo is called with the specified arguments and this bound to the newly created object.
new Foo
is equivalent tonew Foo()
, i.e. if no argument list is specified, Foo is called without arguments.- 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
}
关于javascript - 是否可以在 JS 中重新创建 "new"运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34928689/