码迷,mamicode.com
首页 > 移动开发 > 详细

如何用apply实现一个bind?

时间:2020-02-16 14:42:07      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:调用   argument   script   alt   第一个   inf   com   on()   arguments   

面试题:如何用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
*/

如何用apply实现一个bind?

标签:调用   argument   script   alt   第一个   inf   com   on()   arguments   

原文地址:https://www.cnblogs.com/cwwStayHungryStayFoolish/p/12316674.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!