bind
bind()方法会创建一个新函数。当这个新函数被调用时,bind()的第一个参数将作为它运行的this,之后的一序列参数将会在传递的实参前传入作为它的参数。
由此可以得出bind函数的两个特点:
- 返回一个函数
- 可以传入参数
返回函数的模拟实现
第一个特点:
var foo = {
value: 1
};
function bar() {
console.log(this.value);
}
// 返回了一个函数
var bindFoo = bar.bind(foo);
bindFoo(); // 1
关于指定this的指向,我们可以使用call或者apply实现。
//第一版
Function.prototype.bind2 = function (context) {
var self = this;
return function () {
self.apply(context);
}
}
传参的模拟实现
接下来看第二点,可以传入参数,这个就有点让人费解了,我们在bind的时候,是否可以传参呢?我在执行bind返回的函数的时候,可不可以传参呢?举个例子:
var foo = {
value: 1
};
function bar(name, age) {
console.log(this.value);
console.log(name);
console.log(age);
}
var bindFoo = bar.bind(foo, 'daisy');
bindFoo('18');
// 1
// daisy
// 18
函数需要传age两个参数,竟然还可以在bind的时候,只传一个name,在执行返回的函数的时候,再传另一个参数age!
这可咋办?不急,我们用arguments进行处理:
// 第二版
Function.prototype.bind2 = function (context) {
var self = this;
// 获取bind2函数从第二个参数到最后一个参数
var args = Array.prototype.slice.call(arguments, 1);
return function () {
// 这个时候的arguments是指bind返回的函数传入的参数
var bindArgs = Array.prototype.slice.call(arguments);
self.apply(context, args.concat(bindArgs));
}
}
效果的模拟实现
完成了这两点,最难的部分到了!因为bind还有一个特点就是
一个绑定函数也能使用new操作符创建对象:这种行为就像把原函数当成构造器。提供的this值被忽略,同时调用时的参数被提供给模拟函数。
也就是说当bind返回的函数作为构造函数的时候,bind时指定的this值会失效,但传入的参数依然生效。举个例子:
var value = 2;
var foo = {
value: 1
};
function bar(name, age) {
this.habit = 'shopping';
console.log(this.value);
console.log(name);
console.log(age);
}
bar.prototype.friend = 'kevin';
var bindFoo = bar.bind(foo, 'daisy');
var obj = new bindFoo('18');
console.log(obj);
// undefined
// daisy
// 18
注意:都声明了value值,最后依然返回了undefind,说明绑定的this失效了,如果了解new的模拟实现,就会知道这个时候的this已经指向了obj。
所以我们可以通过修改返回的函数的原型来实现,让我们写一下:
// 第三版
Function.prototype.bind2 = function (context) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
var fbound = function () {
var bindArgs = Array.prototype.slice.call(arguments);
// 当作为构造函数时,this 指向实例,self 指向绑定函数,因为下面一句 `fbound.prototype = this.prototype;`,已经修改了 fbound.prototype 为 绑定函数的 prototype,此时结果为 true,当结果为 true 的时候,this 指向实例。
// 当作为普通函数时,this 指向 window,self 指向绑定函数,此时结果为 false,当结果为 false 的时候,this 指向绑定的 context。
self.apply(this instanceof self ? this : context, args.concat(bindArgs));
}
// 修改返回函数的 prototype 为绑定函数的 prototype,实例就可以继承函数的原型中的值
fbound.prototype = this.prototype;
return fbound;
}
但是在这个写法中,我们直接将 fbound.prototype = this.prototype,我们直接修改 fbound.prototype 的时候,也会直接修改函数的 prototype。这个时候,我们可以通过一个空函数来进行中转:
最终代码
// 最终代码
Function.prototype.bind2 = function (context) {
if (typeof this !== "function") {
throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
}
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
var fNOP = function () {};
var fbound = function () {
return self.apply(this instanceof self ? this : context, args.concat(Array.prototype.slice.call(arguments)));
}
fNOP.prototype = this.prototype;
fbound.prototype = new fNOP();
return fbound;
}