JavaScript 模拟 bind 的实现
作者:Seiya
时间:2019年08月09日
bind
方法
bind() 方法会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数。
模拟实现
bind 和 apply 的区别在于,bind 函数会创建一个新绑定函数,它包装了原函数对象,apply是直接调用。同时,我们还有几个问题需要解决:
问题一
:传参的处理;问题二
:bind 返回的函数作为构造函数的时候,bind 时指定的 this 值会失效,但传入的参数依然生效;
最终实现
Function.prototype.bindFn = function(context) {
let fn = this;
let args = [...arguments].slice(1);
let resFn = function() {
/* 当作为构造函数时,this 指向实例,此时结果为 true,将绑定函数的 this 指向该实例 */
return fn.apply(this instanceof resFn ? this : context, args.concat(...arguments) )
}
/* 修改返回函数的 prototype 为绑定函数的 prototype,实例就可以继承绑定函数的原型中的值 */
function tmp() {}
tmp.prototype = this.prototype;
resFn.prototype = new tmp();
return resFn;
}