js中call和apply用法
时间: 2024-01-05 22:05:07 浏览: 101
在 JavaScript 中,`call` 和 `apply` 是用来改变函数执行上下文(即 `this` 的指向)的两个方法。
`call` 方法的语法是:`function.call(thisArg, arg1, arg2, ...)`。它接收一个参数列表,第一个参数是要设置的 `this` 值,后面的参数是函数的实参。
例如,假设有一个函数 `sayHello`:
```javascript
function sayHello(name) {
console.log("Hello, " + name);
}
```
我们可以使用 `call` 方法来修改 `sayHello` 函数的执行上下文:
```javascript
sayHello.call(null, "John");
```
在上面的例子中,第一个参数 `null` 是要设置的 `this` 值(即执行上下文),后面的参数 `"John"` 是函数 `sayHello` 的实参。这样,函数将以 `null` 作为执行上下文,并输出 "Hello, John"。
与之类似,`apply` 方法的语法是:`function.apply(thisArg, [argsArray])`。它接收一个参数数组,第一个参数是要设置的 `this` 值,第二个参数是一个数组,包含了函数的实参。
使用 `apply` 方法来修改 `sayHello` 函数的执行上下文的示例:
```javascript
sayHello.apply(null, ["John"]);
```
这里的第一个参数仍然是 `null`,第二个参数是包含了 `"John"` 的数组 `["John"]`。
总结一下,`call` 和 `apply` 的区别在于传入参数的方式不同:`call` 方法接收一串参数列表,而 `apply` 方法接收一个参数数组。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)