手写js call apple bind
时间: 2023-12-06 18:04:00 浏览: 41
以下是手写JS中的call、apply和bind方法的实现:
## call
```javascript
Function.prototype.myCall = function (context, ...args) {
context = context || window;
const fn = Symbol('fn');
context[fn] = this;
const result = context[fn](...args);
delete context[fn];
return result;
}
```
## apply
```javascript
Function.prototype.myApply = function (context, args) {
context = context || window;
const fn = Symbol('fn');
context[fn] = this;
const result = context[fn](...args);
delete context[fn];
return result;
}
```
## bind
```javascript
Function.prototype.myBind = function (context, ...args1) {
const fn = this;
return function (...args2) {
return fn.apply(context, [...args1, ...args2]);
}
}
```
以上三个方法的实现都是基于函数原型上的扩展,分别为myCall、myApply和myBind。其中,myCall和myApply的实现过程类似,只是传入参数的方式不同,都是将函数作为对象的属性执行,并将其结果返回。而myBind则是返回一个新函数,绑定了指定的this值和参数列表。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)