prototype.js中Function.prototype.bind方法浅解
2024-10-18 19:22:41
prototype.js中的Function.prototype.bind方法:
Function.prototype.bind = function() {
var __method = this;
var args = Array.prototype.slice.call(arguments);
var object=args.shift();
return function() {
return __method.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
}
}
为所有function对象增加一个新的prototype(原型)方法bind:
- 将调用bind方法的对象保存到__method(方法)变量里面。
- 将调用bind方法时传递的参数转换成为数组保存到变量args。
- 将args数组的第一位[0]元素提取出来保存到变量object。
- 返回一个函数。
这个被返回的函数在再次被调用的时候执行如下操作:
- 使用apply方法将调用bind方法的函数里面的this指针替换为object。
- 将传递到这个匿名函数里面的参数转换为数组,与args数组组合形成一个新的数组,传递给__method方法。
例子:
function o(){
this.num = 1;
var fn = function(arg){alert(this.num+arg)}.bind(this,2);
fn(); //alert(3)
}
new o()
最新文章
- Liferay7 BPM门户开发之38: OSGi模块化Bndtools、Maven、Gradle开发构建入门
- WEB前端html基础中的各类标签介绍
- 49. Search in Rotated Sorted Array &;&; Search in Rotated Sorted Array II
- ntko office 5.0.1.0注册码
- js中的script标签
- PMP考试--关于职业道德
- c#中设置按钮Button为透明
- Ubuntu eclipse :An error has occurred. See the log file
- linux 脚本測试网络速度
- C#中制作MDI窗体
- OpenCV混合高斯模型函数注释说明
- rabbitmq - (消息队列) 的基本原理介绍
- Angular4学习笔记(七)- ViewChild和ViewChildren
- JAVA 课堂测试
- PWM输出
- Java编解码分析
- MongoDB MapReduce 的示例。
- 团队作业4 Alpha冲刺
- spring Controller 层注解获取 properties 里面的值
- ssh框架,工具类调用service层方法