题解 | #修改 this 指向#
修改 this 指向
http://www.nowcoder.com/practice/a616b3de81b948fda9a92db7e86bd171
从例子的角度解题:
function foo() {
var r = bindThis(
function(a, b){return this.test + a + b},
{test: 2})(2, 3);
return r === 7;
}正常情况下,为了改变f的this指向,指向到target,我们会使用bind、call、apply, 就是这样:
f.apply(target, [arg1, arg2, ...]);
bindThis函数在执行完后需要继续执行,因此函数内部需要return一个function以接收参数(2,3)继续执行。
bindThis() {
return function(){...}
}return的函数内部接收了参数(2,3),可以在函数内部使用arguments传递;
且执行完绑定以后,需要返回函数相加后的值,因此需要把f执行完后的值return回去:
function bindThis(f, oTarget) {
return function() {
return f.apply(oTarget, [...arguments]);
};
}
