JavaScript 修正this指针

问题

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

输入例子

bindThis(function(a, b) {
    return this.test + a + b;
}, {test: 1})(2, 3);

输出例子

6

剖析

该问题的要求是:封装一个函数bindThis,该函数有两个参数,第一个参数是一个内部有运用this指针的函数f,第二个参数是一个对象obj,实行bindThis以后,返回一个函数,该函数内里的this就被绑定到obj上面。

function f(a, b) {
    return this.test + a + b;
}

function bindThis(f, obj) {
    //你完成的部份
}

//实行函数
var a = bindThis(f,{test:1});
a(2,3);

解决方法

javascript的三剑客:bind apply call

1、解决方法一:运用bind()

function f(a, b) {
    return this.test + a + b;
}

function bindThis(f, obj) {
    //你完成的部份
    return f.bind(obj);
}

//实行函数
var a = bindThis(f,{test:1});
console.log(a(2,3));
console.log(f(2,3));
6
NaN

2、解决方法二:运用apply()

function bindThis(f, obj) {
    //你完成的部份
    return function () {
        return f.apply(obj, arguments);
    };
}

3、解决方法三:运用call()

function bindThis(f, obj) {
    //你完成的部份
    return function (a,b) {
        return f.call(obj, a,b);
    };
}

call和apply基础的区分:参数差别。apply() 吸收两个参数,第一个是绑定 this 的值,第二个是一个参数数组。而 call() 呢,它的第一个参数也是绑定给 this 的值,然则背面接收的是不定参数,而不再是一个数组,也就是说你能够像日常平凡给函数传参那样把这些参数一个一个通报。

    原文作者:修行的苦行僧
    原文地址: https://segmentfault.com/a/1190000009111716
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞