背景
最近帮助组内进行技术面试,听到有人问了个很有意思的问题,函数bind两次后this指向。平时使用和问的比较多的都是bind接收的参数和bind后的this指向问题,bind多次还真没去想过。但是如果知道bind实现原理的话,这个问题自然迎刃而解。
bind实现
先来个简版
Function.prototype.bind2 = function (context) {
var self = this;
var bindArgs = Array.prototype.slice.call(arguments, 1);
return function () {
var args = bindArgs.concat(Array.prototype.slice.call(arguments));
self.apply(context, args);
}
}
如果清楚这部分实现,bind两次的结果已经很明了了,在第一次bind完this就已经确定了,返回了一个函数出去,这个函数体内不存在this问题,后续无论bind多少次,this都指向第一次bind传入的context,但是后面bind再传入的参数会生效。
附赠个完整版bind
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 bindArgs = Array.prototype.slice.call(arguments, 1);
var fNOP = function () {};
var fbound = function () {
var args = bindArgs.concat(Array.prototype.slice.call(arguments));
self.apply(this instanceof self ? this : context, args);
}
fNOP.prototype = this.prototype;
fbound.prototype = new fNOP();
return fbound;
}
遇到没听过的问题,莫慌,想想实现原理就明白了