ES6 - Reflect.construct()



此方法充當 new 運算子,等效於呼叫 new target(...args)。

語法

下面給出的語法適用於函式 construct(),其中,

  • target 是要呼叫的目標函式。

  • argumentsList 是一個類似陣列的物件,指定了 target 應該呼叫的引數。

  • newTarget 是應使用其原型的建構函式。這是一個可選引數。如果未向此引數傳遞任何值,則其值為 targetparameter

Reflect.construct(target, argumentsList[, newTarget])

示例

以下示例建立一個具有 fullName 屬性的 Student 類。該類的建構函式以 firstName 和 lastName 作為引數。如下所示,使用反射建立 Student 類的物件。

<script>
   class Student{
      constructor(firstName,lastName){
         this.firstName = firstName
         this.lastName = lastName
      }
      
	  get fullName(){
         return `${this.firstName} : ${this.lastName}`
      }
   }
   
   const args = ['Mohammad','Mohtashim']
   const s1 = Reflect.construct(Student,args)
   
   console.log(s1.fullName)

</script>

以上程式碼的輸出如下所示:

Mohammad : Mohtashim
廣告

© . All rights reserved.