call 与 apply 在 JavaScript 中有何区别?
在 JavaScript 中,.call 和 .apply 认为是函数对象的方法。
.call 方法
使用 call 方法计算参数数量。它将一个或多个参数作为对象。如需使用 call 方法:
以下为语法
.call(object, “argument1”, “argument2”);
.apply 方法
若要将数组作为参数,请使用 .apply。它要求将数组作为其第 2 个参数。如需使用 apply 方法:
以下为语法
.apply(object, [“argument1”, “argument[]”]);
示例
下面我们来看一个显示 call 和 apply 两种方法的示例
<!DOCTYPE html>
<html>
<head>
<body>
<script>
var p = {
q: "Hello"
}
function showResult(v) {
document.write(this.q + " " + v);
}
showResult.call(p, "Amit"); // one or more objects as argument
showResult.apply(p, ["World"]); // array as the second argument
</script>
</body>
</head>
</html>
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP