JavaScript - 函数 apply() 方法
函数 apply() 方法
JavaScript 中的函数 apply() 方法允许我们通过为 this 指定一个值并以数组形式提供参数来调用一个函数。
函数 call() 方法和 apply() 方法非常相似,但它们之间的主要区别在于函数 apply() 方法接受一个包含所有函数参数的数组,而函数 call() 方法则接受单独的参数。
与函数 call() 方法相同,我们可以使用 apply() 方法来操作 this 值,并将一个轨道对象赋给 this。
语法
JavaScriot 中 Function apply() 方法的语法如下:
func.apply(thisArg, [arg1, arg2, ... argN]);
参数
thisArg − thisArg 元素表示函数上下文。它是一个对象,其属性是使用"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! 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>
输出
The price of the OD Q6 is: 10000000
使用带有函数参数数组的 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>
输出
Total sum is 87
将 apply() 方法与内置函数结合使用
您还可以将 apply() 方法与内置对象方法结合使用。我们可以使用 apply() 方法调用内置对象方法(例如 Math.max 或 Math.min)。
在下面的示例中,我们将 apply() 方法与内置 JavaScript 函数(Math.max 和 Math.min)结合使用。我们不能直接对数组使用这些方法。我们使用 apply() 方法调用 Math.max 和 Math.min 方法。我们将 null 作为 thisArg 传递,并将包含五个整数的数组作为函数参数传递。
<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: 9 Max element in the array:3
请注意,如果直接对数组使用 Math.max() 或 Math.min() 方法来查找数组中的最大或最小元素,结果将为 NaN。

