bind方法建立一个新函数。调用新函数时,this指向给定的对象,而且将给定的参数列表做为原函数的参数序列的前若干项。bash
当使用new操做符建立bind函数的实例时,bind函数变成构造器,给定的对象参数失效,其他参数仍然有效。app
function myBind(){
var self = this;
// 第一个对象参数
var context = Array.prototype.shift.call(arguments);
// 其他参数
var bindArgs = Array.prototype.slice.call(arguments);
// 临时函数
var fTemp = function(){};
function fn(){
// 合并绑定参数以及调用时参数
var args = bindArgs.concat(Array.prototype.slice.call(arguments));
// 原函数执行(this指向给定对象)
self.apply(context, args);
}
// 临时函数prototype指向原函数prototype
fTemp.prototype = self.prototype;
// 新函数prototype设为临时函数的实例对象(当原函数使用New建立实例)
fn.prototype = new fTemp();
return fn;
}
复制代码