The static method Reflect.apply in JavaScript is employed to invoke a function with the given arguments.
Syntax
Example
Reflect.apply(target, thisArgument, argumentsList)
Parameter
target : It is the target function to call.
thisArgument: This represents the value of this that is supplied for the invocation of target.
ArgumentsList: This refers to an object that resembles an array, detailing the arguments that need to be passed when invoking the target function.
Return
The outcome produced by invoking the designated target function using the provided this value and parameters.
Exceptions
This approach will raise a TypeError in the event that the target is not a callable entity.
Example 1
Example
function g (a, b) {
this.x = a;
this.y = b;
}const obj = {};
Reflect.apply ( g , obj, [33,44] );
console.log( obj );
Output:
Output
Object { x: 33, y: 44 }
Example 2
Example
var whatsThis = function() { console.log(this); }
Reflect.apply(whatsThis, 'hello', []);
// Call a function that takes a variable number of args
var numbers = [3, 20, 1, 55];
console.log(Reflect.apply(Math.max, undefined, numbers));
Output:
Output
"hello"
55
Example 3
Example
console.log(Reflect.apply(Math.floor, undefined, [45]));
console.log(Reflect.apply(String.fromCharCode, undefined, [104, 101,103,105]));
console.log(Reflect.apply(RegExp.prototype.exec, /ab/, ['confabulation']).index);
console.log(Reflect.apply(''.charAt, 'Rahul', [3]));
Output:
Output
45
"hegi"
4
"u"