如何用apply实现一个bind?

面试题:如何用apply实现一个bind?

Function.prototype._bind = function(target) {
    // 保留调用_bind方法的对象
    let _this = this;
    // 接收保存传入_bind方法中的参数,等价于arguments.slice(1),除了第一个参数其余全视作传入参数
    let args = [].slice.call(arguments, 1)
    return function() {
        return _this.apply(target, args)
    }
}

let obj = {
    name: '测试员小陈'
}

// 测试函数
function test(args) {
    console.log('this:', this);
    console.log('我的名字:', this.name);
    console.log('我接收的参数:', args);
}

console.log(test._bind(obj, "I am args")); // output: [Function]

test._bind(obj, "I am args")()

/* 执行结果
*  this: { name: '测试员小陈' }
*  我的名字: 测试员小陈
*  我接收的参数: I am args
*/

猜你喜欢

转载自www.cnblogs.com/cwwStayHungryStayFoolish/p/12316674.html
今日推荐