網站搜尋

javascript - Reflect.construct vs new(此處的物件類型)


在使用 ES6 的 Reflect.construct 之後,我注意到將對象類型作為 new 關鍵字的參數化也可行。

https://jsfiddle.net/mnw349o5/

function Nice() {
    return Date;
}


window.alert(new (Nice())); // will show the date today

window.alert(Reflect.construct(Nice(), [])); // same as above

window.alert(new Nice()); // not the intended

我是否還應該使用在 new 關鍵字上將物件類型作為參數傳遞的方式來創建動態物件,因為這似乎也能正常運作?不使用 Reflect.construct 對專案來說可以少一個 node 模組依賴。

目前我正在使用 harmony-reflect 來 polyfill Reflect,以便我可以在針對 ES5 的 TypeScript 專案中使用它。

答案#1

在你需要使用 Reflect 之前,沒有理由去使用它(在 construct 的情況下,這是用來將 newtarget 設置為任意值的時候)。你不需要它,所以你不應該使用它。