📜  Function.prototype.apply() - Javascript (1)

📅  最后修改于: 2023-12-03 14:41:20.907000             🧑  作者: Mango

Function.prototype.apply() - JavaScript

Function.prototype.apply() is a built-in function in JavaScript that allows you to call a function with a given this value and an array of arguments.

Syntax
function.apply(thisArg, [argsArray])
  • thisArg: The value of this that should be used when calling the function. If null or undefined, the global object will be used.
  • argsArray (optional): An array or an array-like object containing the arguments to pass to the function. If not provided, the function is called with no arguments.
Example

Here's an example of how to use apply() to call a function and pass arguments in an array:

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

const result = sum.apply(null, numbers);

console.log(result); // Output: 6

In this example, we have a function sum that takes three arguments x, y, and z and returns their sum. We also have an array numbers containing the values [1, 2, 3].

Using apply(), we call sum with null as the value of this (since our sum function doesn't rely on any object context) and pass the numbers array as the second argument. The apply() method passes the array values as individual arguments to the sum() function, so effectively, we're calling sum(1, 2, 3).

The result is 6, which we log to the console.

Conclusion

The Function.prototype.apply() method is a powerful way to call a function with a specific this value and a given set of arguments. It's a useful tool to have in your JavaScript arsenal, and it can help you write more flexible and reusable code.