JavaScript 中的 Function apply() 方法允许我们在给定特定的 this 值和以数组形式提供的参数的情况下调用一个函数。
Function call() 和 apply() 方法非常相似,但主要的区别在于 apply() 方法接收一个包含所有函数参数的单一数组,而 call() 方法接收单独的参数。
与 Function call() 方法相同,我们可以使用 apply() 方法来操控 this 值,并可以将任意对象赋值给 this。
语法
JavaScript 中 Function apply() 方法的语法如下:
func.apply(thisArg, [arg1, arg2, ... argN]);
参数
-
thisArg — thisArg 参数代表函数上下文。它是需要使用 this 关键字访问参考函数的对象。
-
[arg1, arg2, ... argN] — 它们是要传递给函数的参数。
返回值
它返回函数返回的结果值。
示例
让我们通过一些示例来理解 JavaScript Function apply() 方法。
不带参数使用 apply() 方法
在下面的代码中,我们定义了一个打印消息的 test() 函数。
我们以标准的方式调用了这个函数,并且使用 apply() 方法来调用该函数而不传递任何参数。输出显示 apply() 方法产生的结果与普通函数调用相同。
<html>
<head>
<title>JavaScript - Function apply() 方法</title>
</head>
<body>
<p id="output1"> </p>
<p id="output2"> </p>
<script>
function test() {
return "函数 test 已被调用!";
}
document.getElementById("output1").innerHTML = test();
document.getElementById("output2").innerHTML = test.apply();
</script>
</body>
</html>
输出:
函数 test 已被调用!
函数 test 已被调用!
仅带 this 参数使用 apply() 方法
在下面的代码中,car 对象包含了三个不同的属性。我们将 car 对象作为 apply() 方法的 thisArg 参数传递。
在 showCar() 函数中,我们使用 this 关键字访问 car 对象的属性,并将其打印到输出中。
<html>
<head>
<title>JavaScript - Function apply() 方法</title>
</head>
<body>
<p id="output"> </p>
<script>
function showCar() {
return "这辆 " + this.name + " " +
this.model + " 的价格是: " + this.price;
}
let car = {
name: "OD",
model: "Q6",
price: 10000000,
}
document.getElementById("output").innerHTML = showCar.apply(car);
</script>
</body>
</html>
输出:
这辆 OD Q6 的价格是: 10000000
带函数参数数组使用 apply() 方法
在下面的示例中,我们将 nums 对象作为 apply() 方法的第一个参数传递。之后,我们将参数数组作为 apply() 方法的参数传递。
在 printSum() 函数中,我们使用 this 关键字访问对象属性,并使用函数参数访问函数参数。
<html>
<head>
<title>JavaScript - Function apply() 方法</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 = "总和是 " + ans;
</script>
</body>
</html>
输出:
总和是 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() 方法</title>
</head>
<body>
<p id="output-max"> 数组中的最大元素: </p>
<p id="output-min"> 数组中的最小元素: </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>
输出:
数组中的最大元素: 9
数组中的最小元素: 3
注意如果你直接对数组使用 Math.max() 或 Math.min() 方法来查找数组中的最大或最小元素,结果将会是 NaN。