JavaScript Basics: Reflect.construct

in #javascript6 years ago (edited)

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

Sort:  

programing is a language of computer.i like this specialy,mathlab,fortan,c/c++.excelent
thanks for sharing

Good work.. You are writing nice and doing good for community.. I always told that computer is not my subject but always happy to see good work here.. And respect good teachers also

useful post on construct.

graet writing dear lovely friend @ghasemkiani. i all time like support and love your post and i well never forget you.

keep it up dear
@ghasemkiani

educative

Helpful post. thanks for the example.

بسیار عالی
بهترین لحظات را براتون آرزو میکنم

چه جالب
پس تعریف شی بصورت بالا انجام میشه در
reflect
ممنون

Wow amazing programming...thaNks for sharing...

Good information about reflect construct in javascript. You are guiding us like a teacher
Thank you very much @ghasemkiani

Coin Marketplace

STEEM 0.32
TRX 0.11
JST 0.034
BTC 66654.57
ETH 3250.95
USDT 1.00
SBD 4.33