您的位置:首页 > Web前端 > JavaScript

prototype.js中Function.prototype.bind方法浅解

2014-06-21 18:55 495 查看
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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: