前端挑战之js编程题(1)

来源:互联网 发布:windows只能进安全模式 编辑:程序博客网 时间:2024/06/07 14:23

题目要求:

封装函数 f ,使 f 的 this 指向指定的对象

思路:

看到题目要求,首先应该想到js 中改变this 指向的三个方法 (bind , apply ,call),这样就能够解决该问题了。


方案1:

function bindThis(f,oTarget){

return function (){

return f.apply(oTarget,arguments);

};

}

方案2:

function bindThis(f,oTarget){

return f.bind(oTarget);

}


方案3:

function bindThis(f, oTarget) {
    return function(x,y){
        return f.call(oTarget,x,y);
    };

}

原创粉丝点击