函数 apply() 方法
JavaScript 中的 Function apply() 方法允许我们调用一个函数,给定一个特定的 this 值和作为数组提供的参数。
Function call() 和 apply() 方法非常相似,但它们之间的主要区别在于函数 apply() 方法接受包含所有函数参数的单个数组,而函数 call() 方法接受单个参数。
与 Function call() 方法相同,我们可以使用 apply() 方法来操作 this 值,并可以为 this 分配一个轨道对象。
语法
JavaScriot 中 Function apply() 方法的语法如下 -
func.apply(thisArg, [arg1, arg2, ... argN]);
参数
- thisArg − 'thisArg' grument 表示函数上下文。它是一个对象,其属性是使用 'this' 关键字访问引用函数所必需的。
- [arg1, arg2, ...argN] − 它们是要传递给函数的参数。
返回值
它返回从函数返回的结果值。
例子
让我们通过一些示例来了解 JavaScript 函数 apply() 方法。
在不传递参数的情况下使用 apply() 方法
在下面的代码中,我们定义了 test() 函数,该函数在输出中打印消息。
我们以标准方式调用函数,并使用 apply() 方法,而不传递任何参数来调用函数。输出显示 apply() 方法给出与普通函数调用相同的输出。
<html>
<head>
<title> JavaScript - Function apply() method </title>
</head>
<body>
<p id = "output1"> </p>
<p id = "output2"> </p>
<script>
function test() {
return "The function test is invoked!";
}
document.getElementById("output1").innerHTML = test();
document.getElementById("output2").innerHTML = test.apply();
</script>
</body>
</html>
输出
The function test is invoked!
仅使用带有此参数的 apply() 方法
在下面的代码中,'car' 对象包含三个不同的属性。我们将 car 对象作为 apply() 方法的 'thisArg' 参数传递。
在 showCar() 函数中,我们使用 'this' 关键字访问 car 对象的属性,并将其打印到输出中。
<html>
<head>
<title> JavaScript - Function apply() method </title>
</head>
<body>
<p id = "output"> </p>
<script>
function showCar() {
return "The price of the " + this.name + " " +
this.model + " is: " + this.price;
}
let car = {
name: "OD",
model: "Q6",
price: 10000000,
}
document.getElementById("output").innerHTML = showCar.apply(car);
</script>
</body>
</html>
输出
将 apply() 方法与函数参数数组一起使用
在下面的示例中,我们将 nums 对象作为 apply() 方法的第一个参数传递。之后,我们将参数数组作为 apply() 方法的参数传递。
在 printSum() 函数中,我们使用 'this' 关键字访问对象属性,使用函数参数访问函数参数。
<html>
<head>
<title> JavaScript - Function apply() method </title>
</head>
<body>
<p id = "output"> </p>
<script>
function printSum(p1, p2) {
return this.num1 + this.num2 + p1 + p2;
}
const nums = {
num1: 5,
num2: 10,
}
const ans = printSum.apply(nums, [40, 32]);
document.getElementById("output").innerHTML = "Total sum is " + ans;
</script>
</body>
</html>
输出
使用带有内置函数的 apply() 方法
您还可以将 apply() 方法与内置对象方法一起使用。我们可以使用 apply() 方法调用内置的对象方法(例如 Math.max 或 Math.min)。
在下面的示例中,我们使用带有内置 JavaScript 函数 Math.max 和 Math.min 的 apply() 方法。我们不能直接将这些方法用于数组。我们使用 apply() 方法调用 Math.max 和 Math.min 方法。我们将 null 作为 thisArg 传递,将 5 个整数的数组作为函数参数传递。
<html>
<head>
<title> JavaScript - Function apply() method </title>
</head>
<body>
<p id = "output-max"> Max element in the array: </p>
<p id = "output-min"> Max element in the array:</p>
<script>
const numbers = [7, 6, 4, 3, 9];
document.getElementById("output-max").innerHTML += Math.max.apply(null, numbers);
document.getElementById("output-min").innerHTML += Math.min.apply(null, numbers);
</script>
</body>
</html>
输出
Max element in the array:3
请注意,如果你直接对数组使用 Math.max() 或 Math.min() 方法来查找数组中的 max 或 min 元素,结果将是 NaN。