js bind的實現

call,apply,bind都是用來挾持對象或者說更改this指向的,可是區別仍是有的,call 傳參是 fn.call(this,1,2,3) apply傳參是 fn.apply(this,[1,2,3])javascript

而前二者是當即執行的,後者Bind是返回一個函數 var foo = fn.bind(this)  foo()java

看到一個關於美團面試題是如何實現js bind面試

      if (typeof Function.prototype.bind === "undefined"){
	  Function.prototype.bind = function (thisArgs){
	    var fn = this,
	        slice = Array.prototype.slice,
	        args = slice.call(arguments, 1);//都是爲了截取參數
	    return function (){
	      return fn.apply(thisArgs, args.concat(slice.call(arguments)));
	    }
	  }
	}

代碼來自書籍 《javaScript 模式》數組

其實結合上ES6能夠更簡潔:app

Function.prototype.bind1 = function (thisArgs){
	var fn = this,//foo
	//arguments 是類數組,支持for循環,但不支持數組的方法
//	args = [].slice.call(arguments, 1);//截取參數 5
	args = Array.from(arguments).slice(1);//截取參數 5
	return function (){
	   return fn.apply(thisArgs,args);
	}
}
	var m = {	
  	  "x" : 1
	};
	function foo(y) {	
    	console.log(this.x + y);
	}
//	foo.apply(m, [5]);
//	foo.call(m, 5);
	var foo1 = foo.bind1(m,5);
	foo1();

上面的return函數也換成箭頭函數的話就更加簡潔了。函數

 

Function.prototype.bind1 = function (thisArgs){
  args = Array.from(arguments).slice(1);//截取參數 5
  return ()=>this.apply(thisArgs,args)
}

 

箭頭函數注意:只有一句的時候能夠省略return,而後前面的fn也能夠省略了。this

相關文章
相關標籤/搜索