实现一个简单的 bind polyfill

1,264 阅读1分钟

普通实现

定义:bind 方法返回一个新函数,函数的 this 被 bind 的第一个参数指定,bind 其余的参数将作为新函数的参数待新函数被调用时使用

if (!Function.prototype.bind){
	Function.prototype.bind = function (ctx) {		
		let arg = Array.prototype.slice.call(arguments, 1);
		let self = this;
		return function (){
			return self.apply(ctx, arg.concat(Array.prototype.slice.call(arguments)));
		}
	}
}

let module = {
  add: function(a, b) {
    return a + b;
  }
}

let obj = {};
let add = module.add.bind(obj, 1);
console.log(add(2));

当 bind 碰到 new

当使用被 bind 绑定过的构造函数来创建实例时,绑定的 this 会被忽略,表现为和正常实例化对象一致,不过提供的参数列表仍然会插入到构造函数调用时的参数列表之前

if (!Function.prototype.bind){
	Function.prototype.bind = function (ctx) {		
    	let arg = Array.prototype.slice.call(arguments, 1);
    	let self = this;
    	let fBond = function (){
    		let _this = this instanceof fBond ? this : ctx;
    		return self.apply(_this, arg.concat(Array.prototype.slice.call(arguments)));
    	}
    	if (this.prototype) {
          fBond.prototype = this.prototype
        } 
    	return fBond;
    }
}