我正试图找到一个很好的理由来使用 Reflect.construct
来实现我以前无法实现的值得注意的事情。
我不是在寻找像 one here 这样的答案,因为那个例子似乎不是很有用。比如我为什么要写
function greetingFactory(name) {
return Reflect.construct(Greeting, [name]);
}
什么时候可以写
function greetingFactory(name) {
return new Greeting(name);
}
?
您知道 Reflect.construct
的任何显着用例吗?
编辑:好像我自己找到了一个用例,但我不确定它是否坚固以及它是否不会散架,但基本上我似乎可以制作 new.target
像这样编写 ES5 风格的类:
function Foo() {
console.log('Foo, new.target:', new.target)
this.name = "foo"
}
Foo.prototype.sayHello = function sayHello() {
return this.name
}
function Bar() {
console.log('Bar, new.target:', new.target)
let _ = Reflect.construct(Foo, [], new.target)
_.name = _.name + " bar"
return _
}
Bar.prototype = Object.create(Foo.prototype)
Bar.prototype.sayHello = function() {
return "Hello " + Foo.prototype.sayHello.call(this) + "!"
}
function Baz() {
console.log('Baz, new.target:', new.target)
let _ = Reflect.construct(Bar, [], new.target)
_.name = _.name + " baz"
return _
}
Baz.prototype = Object.create(Bar.prototype)
Baz.prototype.sayHello = function() {
return Bar.prototype.sayHello.call(this) + " Hello again!"
}
let baz = new Baz
console.log(baz.sayHello())
最酷的是 this
在原型(prototype)方法中符合预期!
最佳答案
我所知道的 Reflect.construct
的三个用例是:
在代理中使用它
construct
trap获得默认行为(或获得略微修改的默认行为)。当您需要使用其元素需要作为离散参数传递的数组调用构造函数时,使用它来避免创建和使用迭代器。你可以做
t = new Thing(...theArray);
但这涉及创建和使用迭代器,而
t = Reflect.construct(Thing, theArray);
不使用迭代器,它的工作要少得多(这通常并不重要;这是针对您知道时间至关重要的情况)。 (
construct
不是迭代器,而是使用length
并直接访问0
、1
等属性。 )在 ES2015 之前,这些选项都不可用。相反,您必须这样做:
t = Thing.apply(Object.create(Thing.prototype), theArray);
与 ES5 构造函数一起工作。 (它不适用于通过
<class
创建的 ES2015+ 构造函数,但您不需要它——您可以使用上述两个选项之一。)在构造
Error
或Array
的子类型实例或 Web 组件(一些人们 don't like to useclass
,并且在可能需要转译的项目中有很好的论据)。 (也就是说,Reflect.construct
也不能完美填充。)
关于javascript - Reflect.construct 让我们做了哪些以前做不到的事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41514964/