Function.prototype.bind : 可以让所有函数的隐式原型上有一个bind
Function.prototype.bind = function() {
}
实现效果:
1、bind的第一个形参是要绑定给函数的上下文:
Function.prototype.bind = function(context) {
var fn = this;
return function() {
return fn.apply(context);
}
}
2、 可以传递多个参数
-
使用例子:
- 第一个参数是:绑定给调用它的函数的上下文
- 其他参数将会作为预设参数传递给这个参数
let foo = function() { console.log(arguments); } foo.bind(null,"a","b")("c","d","e"); // {"1":"a","2":"b","3":"c","4":"d","5":"e"}
-
实现 方法一【ES6】:
只要在返回的值上将函数合并上去就行
Function.prototype.bind = function(context,...args){ var fn = this; return function(...rest) { return fn.apply(context,[...args,...rest]); } }
-
实现方法二【ES5】:
Function.prototype.bind = function() { var args = Array.prototype.slice.call(arguments); var context = arr.splice(0,1)[0]; var fn = this; return function() { let rest = Array.prototype.slice.call(arguments); return fn.apply(context,args.concat(rest)); } }
3、把函数的原型保留下来
Function.prototype.bind = function() {
var args = Array.prototype.slice.call(arguments);
var context = args.splice(0,1)[0];
var fn = this;
var res = function() {
let rest = Array.prototype.slice.call(arguments);
return fn.apply(context,args.concat(rest));
}
if(this.prototype) {
res.prototype = this.prototype;
}
return res;
}
4、 还需要找到一种方法来判断是否对bind之后的结果使用了new操作符
Function.prototype.bind = function() {
var args = Array.prototype.slice.call(arguments);
var context = args.splice(0,1)[0];
var fn = this;
var noop = function() {}
var res = function() {
let rest = Array.prototype.slice.call(arguments);
// this只和运行的时候有关系,所以这里的this和上面的fn不是一码事,new res()和res()在调用的时候,res中的this是不同的东西
return fn.apply(this instanceof noop ? this : context, args.concat(rest));
}
if(this.prototype) {
noop.prototype = this.prototype;
}
res.prototype = new noop();
return res;
}