Javascript - Apply

Table of Contents

About

apply permits to call a function stored in a variable specifying:

If you want to execute dynamically a string that stores javascript, you use the eval function.

Example

  • A function that we will call with apply that:
    • print the name property of the this execution context
    • print the arguments
let dynamicCall = function(){
  
  console.log("The name property of this is: "+this.name);
  console.log("The arguments are: "+Object.values(arguments).join(", "));
  
}
  • The Calls
console.log("First Call");
dynamicCall.apply( { name: "First Call" }, ["arg1", "arg2"] )

console.log("Second Call");
dynamicCall.apply( { name: "Second Call" }, ["arg3", "arg4"] )
  • Output:

Powered by ComboStrap