题解 | #修改 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]);
  };
}
全部评论

相关推荐

雪飒:我也遇见过,我反问他有考虑来华为od吗?
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务