ghasemkiani avatar

JavaScript Basics: Reflect.construct

ghasemkiani

Published: 16 Feb 2018 › Updated: 16 Feb 2018JavaScript Basics: Reflect.construct

JavaScript Basics: Reflect.construct

The method Reflect.construct helps construct a new instance from a constructor function given an array of arguments. It has a functionality similar to the new operator:

    function Employee (firstname, lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }
    
    let employee1 = new Employee("John", "Doe");
    let employee2 = Reflect.construct(Employee, ["Jane", "Doe"]);
    
    // This can also be done with the spread operator:
    let args = ["John", "Smith"];
    let employee3 = new Employee(...args);

It is generally useful to have an alternative for the new operator, specially when we have an array of arguments. Even though this particular problem has been alleviated in ES6 with the introduction of the spread operator(...). (See the last line in the example code above.)


Related Posts

Leave JavaScript Basics: Reflect.construct to:

Written by

Read more #javascript posts


Best Posts From ghasemkiani

We have not curated any of ghasemkiani's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From ghasemkiani