C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
JavaScript Reflect.construct() MethodThe static Reflect.construct() method allows to invoke a constructor with a variable number of arguments. It gives also the added option to specify a different prototype. SyntaxReflect.construct(target, argumentsList[, newTarget]) Parametertarget: It is the target function to call. argumentsList: It is an array-like object specifying the arguments with which target should be called. newTarget: It is a constructor whose prototype should be used. See also the new.target operator. If newTarget is not present, it will treat as a target. ReturnThis method returns a new instance of the target (or newTarget if present), initialized by the target as a constructor with the given arguments. ExceptionsThis exception will throw a TypeError if target or newTarget are not constructors. Example 1const a = new Array(1,2,3); const b = Reflect.construct ( Array, [1,2,3] ); console.log(a); console.log(b); Output: [1, 2, 3] [1, 2, 3] Example 2function func1(a, b, c) { this.sum = a + b + c; } const args = [1, 2, 3]; const object1 = new func1(...args); console.log(object1.sum); Output: 6 Example 3function func1(a, b, c) { this.sum = a + b + c; } function func2(a, b, c) { this.sum = a + b + c; } const args2 = [1, 4, 3]; const args = [1, 2, 3]; const object1 = new func1(...args); const object2 = Reflect.construct(func2, args2); console.log(object2.sum); console.log(object1.sum); Output: 8 6
Next TopicJavaScript Reflect
|