javascript中利用柯里化函数实现bind方法【推荐】
作者:jingxian 时间:2024-05-02 17:29:26
• 柯理化函数思想:一个js预先处理的思想;利用函数执行可以形成一个不销毁的作用域的原理,把需要预先处理的内容都储存在这个不销毁的作用域中,并且返回一个小函数,以后我们执行的都是小函数,在小函数中把之前预先存储的值进行相关的操作处理即可;
• 柯里化函数主要起到预处理的作用;
• bind方法的作用:把传递进来的callback回调方法中的this预先处理为上下文context;
/**
* bind方法实现原理1
* @param callback [Function] 回调函数
* @param context [Object] 上下文
* @returns {Function} 改变this指向的函数
*/
function bind(callback,context) {
var outerArg = Array.prototype.slice.call(arguments,2);// 表示取当前作用域中传的参数中除了fn,context以外后面的参数;
return function (){
var innerArg = Array.prototype.slice.call(arguments,0);//表示取当前作用域中所有的arguments参数;
callback.apply(context,outerArg.concat(innerArg));
}
}
/**
* 模仿在原型链上的bind实现原理(柯理化函数思想)
* @param context [Object] 上下文
* @returns {Function} 改变this指向的函数
*/
Function.prototype.mybind = function mybind (context) {
var _this = this;
var outArg = Array.prototype.slice.call(arguments,1);
// 兼容情况下
if('bind' in Function.prototype) {
return this.bind.apply(this,[context].concat(outArg));
}
// 不兼容情况下
return function () {
var inArg = Array.prototype.slice.call(arguments,0);
inArg.length === 0?inArg[inArg.length]=window.event:null;
var arg = outArg.concat(inArg);
_this.apply(context,arg);
}
}
标签:javascript,柯里化,bind方法
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
asp fso创建与删除文件与文件夹
2008-12-31 16:07:00
100%点击区的滑动门
2007-06-14 22:00:00
pytorch的Backward过程用时太长问题及解决
2022-12-11 00:16:06
![](https://img.aspxhome.com/file/2023/9/81649_0s.png)
Python程序设计入门(1)基本语法简介
2023-09-12 05:03:31
Win10下Python环境搭建与配置教程
2023-08-24 03:25:18
![](https://img.aspxhome.com/file/2023/3/61453_0s.png)
Python实现自动发送邮件功能
2021-04-01 14:41:55
![](https://img.aspxhome.com/file/2023/7/109577_0s.png)
python爬虫Scrapy框架:媒体管道原理学习分析
2022-11-23 15:07:03
![](https://img.aspxhome.com/file/2023/8/87738_0s.jpg)
SQLite5-使用Python来读写数据库
2024-01-15 23:44:08
![](https://img.aspxhome.com/file/2023/2/78662_0s.png)
利用Python多线程实现图片下载器
2022-02-12 06:07:41
![](https://img.aspxhome.com/file/2023/5/131125_0s.jpg)
Go语言操作Excel利器之excelize类库详解
2024-04-28 09:12:47
Python接口自动化判断元素原理解析
2022-09-04 18:33:58
CSS关于Border你可能会不注意的东西
2007-10-20 13:50:00
![](https://img.aspxhome.com/file/UploadPic/200710/20/20071020135623390s.gif)
利用python list完成最简单的DB连接池方法
2022-04-19 18:38:00
![](https://img.aspxhome.com/file/2023/9/95319_0s.jpg)
Python深度学习之实现卷积神经网络
2021-08-11 01:57:01
![](https://img.aspxhome.com/file/2023/3/131603_0s.png)
IntelliJ IDEA下的SVN使用(傻瓜式教学)
2023-07-20 05:36:58
![](https://img.aspxhome.com/file/2023/0/131830_0s.png)
浅谈Golang的方法传递值应该注意的地方
2024-02-12 07:40:20
![](https://img.aspxhome.com/file/2023/0/107310_0s.jpg)
JavaScript实现图片放大预览效果
2023-08-23 02:41:17
![](https://img.aspxhome.com/file/2023/8/56098_0s.png)
Python Pandas学习之数据离散化与合并详解
2022-09-28 20:12:07
![](https://img.aspxhome.com/file/2023/3/128513_0s.png)
Python 多个图同时在不同窗口显示的实现方法
2022-07-02 01:20:35
使用python的pexpect模块,实现远程免密登录的示例
2022-10-19 18:30:22