js 实现bind

实现bind的步骤,我们可以分解成为三部分:

  • 修改this指向
  • 动态传递参数
  • 兼容new关键字
Function.prototype.mBind = function (context) {
    // 判断调用对象是否为函数
    if (typeof this !== "function") {
        throw new TypeError("Error");
    } 
    // 获取参数
    const args = [...arguments].slice(1),
             self = this;

    return function Fn() {
        // 根据调用方式,传入不同绑定值
        oo = this instanceof Fn ? new self(...arguments) : context  // 
        return  self.apply(oo, args.concat(...arguments)); 
    }
}

// 测试
function p(name, age) {
    console.log('打印:', this.value, name, age);
} 
var obj = {
    value: '易'
}
 
p.mBind(obj, '四鸹岽')(16);  //打印: 易  四鸹岽 16


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容