ES6 - Reflect.construct ()

Questo metodo funge da operatore new ed equivale a chiamare new target (... args).

Sintassi

La sintassi fornita di seguito è per la funzione construct(), dove,

  • target è la funzione di destinazione da chiamare.

  • argumentsList è un oggetto simile a un array che specifica gli argomenti con cui deve essere chiamato target.

  • newTargetè il costruttore il cui prototipo dovrebbe essere utilizzato. Questo è un parametro opzionale. Se nessun valore viene passato a questo parametro, il suo valore ètargetparameter.

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

Example

The following example creates a class Student with a property fullName. The constructor of the class takes firstName and lastName as parameters. An object of the class Student is created using reflection as shown below.

<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>

The output of the above code will be as follows −

Mohammad : Mohtashim