关注微信公众号“知之洲” 即可获得大量优质前端干货。 ⁽⁽ଘ(ˊᵕˋ)ଓ⁾⁾
在写bind之前,我们得了解bind的基本用法。
bind的基本用法是直接使用bind方法绑定一个函数的上下文。类似这个样子
let foo = function(){
console.log(this);
}
let boo = foo.bind({content: "hello"});
foo(); // global / window
boo(); // {content: "hello"}
先实现上面的效果,因为bind函数是给所有函数来调用的,所以应该实现一个Function.prototype.bind,这样就可以让所有函数的隐式原型上都会有一个bind了。
Function.prototype.bind = function() {
// TODO
}
bind的第一个形参是要绑定给函数的上下文,所以再完善一下上面的代码
Function.prototype.bind = function(context) {
var fn = this;
return function() {
return fn.apply(context);
}
}
这个时候上面的效果就实现了,但是只能给bind传递一个参数。
真正的bind函数是可以传递多个参数的,第一个参数是要绑定给调用它的函数的上下文,其他的参数将会作为预设参数传递给这个函数,如下所示
let foo = function(){
console.log(arguments);
}
foo.bind(null,"a","b")("c","d","e"); // {"1":"a","2":"b","3":"c","4":"d","5":"e"}
为了实现上面的效果,我们发现只要在返回的值上将函数合并上去就行了
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 = args.splice(0,1)[0];
var fn = this;
return function() {
let rest = Array.prototype.slice.call(arguments);
return fn.apply(context, args.concat(rest));
}
}
上面的方法已经能够解决绝大多数的bind的需求了,但是上面没有考虑在对bind之后的函数使用new操作符的情况。请看下面这个例子
let foo = function() {
this.content = "hello";
}
let boo = foo.bind({content:"bye"});
let res = new boo();
console.log(res); // {content:"hello"}
通过上面的例子,可以知道在使用bind对一个函数绑定了上下文之后,得到的函数使用new操作符进行操作之后,这个结果的上下文并不受传递给bind的上下文影响,也就是使用new操作符的时候,传递给bind的第一个参数是会被忽略掉的。
另外要注意的一点是,我们如果直接像下面这样操作是会出错的。
let foo = function() {
this.content = "hello";
}
let boo = new foo.bind({content:"bye"}); // Uncaught TypeError: foo.bind is not a constructor
因此必须考虑把函数的原型保留下来。
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;
}
我们还需要再找到一种方法来判断是否对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;
}
关注微信公众号“知之洲” 即可获得大量优质前端干货。 ⁽⁽ଘ(ˊᵕˋ)ଓ⁾⁾