實現一個簡單的 bind polyfill

普通實現

定義:bind 方法返回一個新函數,函數的 this 被 bind 的第一個參數指定,bind 其他的參數將做爲新函數的參數待新函數被調用時使用app

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;
    }
}

複製代碼
相關文章
相關標籤/搜索